/* eslint-disable no-extend-native */
(function(window, document) {
    var TencentCaptchaAppId = '2018904000';
    // IE木有indexOf函数..
    if (!Array.indexOf) {
        Array.prototype.indexOf = function(obj) {
            for (var i = 0; i < this.length; i++) {
                if (this[i] === obj) {
                    return i;
                }
            }
            return -1;
        };
    }
    // IE也没有trim
    String.prototype.trim = function() {
        // 用正则表达式将前后空格
        // 用空字符串替代。
        return this.replace(/(^\s*)|(\s*$)/g, '');
    };
    // Array的shuffle函数
    Array.prototype.shuffle = function() {
        for (
            var j, x, i = this.length;
            i;
            j = parseInt(Math.random() * i), x = this[--i], this[i] = this[j], this[j] = x
        );
        return this;
    };

    Array.prototype.sum = function() {
        var sum = 0;
        for (var i = 0; i < this.length; i++) {
            sum += this[i];
        }
        return sum;
    };

    // strip函数
    String.prototype.strip = function() {
        return this.replace(/^\s*(.*?)\s*$/, '$1');
    };

    // parseInt polyfill
    if (Number.parseInt === undefined) {
        Number.parseInt = window.parseInt;
    }

    // 全局的ajax访问，处理ajax清求时异常
    window.$ &&
        $.ajaxSetup({
            complete: function(XMLHttpRequest, textStatus) {
                // 通过XMLHttpRequest取得响应结果
                var res = XMLHttpRequest.responseText;
                try {
                    var jsonData = JSON.parse(res);
                    // jsonData.state !== -1 未超时; jsonData.state !== 0 其他异常
                    if (jsonData.state !== -1 && jsonData.state !== 0) {
                        window.setupRegisterOrLoginTrack && window.setupRegisterOrLoginTrack();
                    }
                } catch (e) {}
            }
        });

    // 模仿python的使用习惯, 0|[]|{}|""这些都返回false

    function isNotEmpty(obj) {
        if (typeof obj === 'undefined' || obj == null) {
            return false;
        }
        if (typeof obj === 'function') {
            return true;
        }
        if (obj.constructor == Number) {
            if (obj) {
                return true;
            } else {
                return false;
            }
        } else if (typeof obj === 'string') {
            if (obj != '') {
                return true;
            } else {
                return false;
            }
        } else {
            for (var prop in obj) {
                if (obj.hasOwnProperty(prop)) {
                    return true;
                }
            }
            return false;
        }
    }

    // 重载String.format方法,使格式化字符串更方便
    // 调用方法
    // "{0},{1},hehe".format(["hello","world"]); //hello,world,hehe
    // "数学={数学},语文={语文},hou".format({"数学":100,"语文":95});//数学=100,语文=95,hou
    var Overload = function(fn_objs) {
        var is_match = function(x, y) {
            if (x == y) return true;
            if (x.indexOf('*') == -1) return false;

            var x_arr = x.split(',');
            var y_arr = y.split(',');
            if (x_arr.length != y_arr.length) return false;

            while (x_arr.length) {
                var x_first = x_arr.shift();
                var y_first = y_arr.shift();
                if (x_first != '*' && x_first != y_first) return false;
            }
            return true;
        };
        var ret = function() {
            var args = arguments;
            var args_len = args.length;
            var args_types = [];
            var args_type;
            var fn_objs = args.callee._fn_objs;
            var match_fn = function() {};

            for (var i = 0; i < args_len; i++) {
                var type = typeof args[i];
                type == 'object' && args[i].length > -1 && (type = 'array');
                args_types.push(type);
            }
            args_type = args_types.join(',');
            for (var k in fn_objs) {
                if (is_match(k, args_type)) {
                    match_fn = fn_objs[k];
                    break;
                }
            }
            return match_fn.apply(this, args);
        };
        ret._fn_objs = fn_objs;
        return ret;
    };

    String.prototype.format = Overload({
        array: function(params) {
            var reg = /{(\d+)}/gm;
            return this.replace(reg, function(match, name) {
                return params[~~name];
            });
        },
        object: function(param) {
            var reg = /{([^{}]+)}/gm;
            return this.replace(reg, function(match, name) {
                return param[name];
            });
        }
    });

    function inputLimitZero(val) {
        return val.replace(/[^\d]/g, '').replace(/^0{1,}/g, '');
    }

    function load_path(path) {
        if (!path || path.length === 0) {
            throw new Error('argument "path" is required !');
        }
        var head = document.getElementsByTagName('head')[0];
        var script = document.createElement('script');
        script.src = path;
        script.type = 'text/javascript';
        head.appendChild(script);
    }

    // 简单实现in的判断

    function check_in(obj, seq) {
        return $.inArray(obj, seq) !== -1;
    }

    function is_equal(obj1, obj2) {
        if (obj1.constructor !== obj2.constructor) return false;
        var aMemberCount = 0;
        for (var a in obj1) {
            if (!obj1.hasOwnProperty(a)) continue;
            if (
                typeof obj1[a] === 'object' && typeof obj2[a] === 'object'
                    ? !obj1[a].equals(obj2[a])
                    : obj1[a] !== obj2[a]
            ) {
                return false;
            }
            ++aMemberCount;
        }
        for (var b in obj2) {
            if (obj2.hasOwnProperty(b)) --aMemberCount;
        }
        return !aMemberCount;
    }

    // 复制对象

    function copy_obj(obj) {
        if (obj.constructor === Array) {
            var new_obj_list = [];
            for (var i = 0; i < obj.length; i++) {
                var item = obj[i];
                new_obj_list.push(copy_obj(item));
            }
            return new_obj_list;
        } else if (obj.constructor === Number || obj.constructor === String) {
            var num = obj;
            return num;
        } else {
            return $.extend(true, {}, obj);
        }
    }

    // 给定一个dom元素，得到与它最近的指定类型的parent元素(jquery类型)

    function get_parent(obj, parent_type) {
        var $parent = $(obj).parent();
        while ($parent.length > 0 && $parent[0].nodeName !== parent_type.toUpperCase()) {
            $parent = $parent.parent();
        }
        return $parent;
    }

    // 阈值手机验证
    function ajaxGet(url, callback) {
        $.ajax({
            url: url,
            type: 'GET',
            contentType: 'application/json', // 不校验签名
            dataType: 'JSON',
            success: function(ret) {
                callback && callback(ret);
            }
        });
    }

    function ajaxPost(url, data, callback, fail_callback) {
        // 保存提示
        var secure_key = $.cookie('_xsrf') || '';
        if (isNotEmpty(secure_key)) {
            data['_xsrf'] = secure_key;
        }
        var is_edit = url.indexOf('edit/ajax') !== -1;
        var isCopyScoreUrl = url == '/edit/ajax_batch_score_copy_setting/'; // 是否是复制分值url
        if (is_edit && !isCopyScoreUrl) {
            if (typeof window.client_uuid !== 'undefined') {
                window.loadMack({
                    off: 'on',
                    Limg: 1,
                    text: '加载中...',
                    set: 0
                });
                data['client_uuid'] = window.client_uuid;
                SavePrompt();
            }
        }
        isNotEmpty(fail_callback)
            ? (fail_callback = fail_callback)
            : (fail_callback = function() {});
        $.ajax({
            url: url,
            data: data,
            dataType: 'JSON',
            type: 'POST',
            timeout: 60000,
            error: fail_callback,
            success: function(ret) {
                if (Number(ret.status) === 200) {
                    if (ret.hasOwnProperty('edit_valid')) {
                        if (!ret.edit_valid) {
                            edit_lock_alert();
                            return;
                        }
                    }
                    if (isNotEmpty(callback)) {
                        callback(ret);
                    }
                    if (is_edit && !ret.err_msg) {
                        SavePrompt(true);
                        $('.loadCon,.loadMack').remove();
                    }
                }
            }
        });
    }

    function syncPost(url, data, callback) {
        // 保存提示
        var secure_key = $.cookie('_xsrf');
        if (isNotEmpty(secure_key)) {
            data['_xsrf'] = secure_key;
        }
        var is_edit = url.indexOf('edit/ajax') !== -1;
        if (is_edit) {
            data['client_uuid'] = window.client_uuid;
            SavePrompt();
        }
        $.ajax({
            url: url,
            data: data,
            dataType: 'JSON',
            type: 'POST',
            async: false,
            success: function(ret) {
                if (Number(ret.status) === 200) {
                    if (ret.hasOwnProperty('edit_valid')) {
                        if (!ret.edit_valid) {
                            edit_lock_alert();
                            return;
                        }
                    }
                    if (isNotEmpty(callback)) {
                        callback(ret);
                    }
                }
                if (is_edit) {
                    SavePrompt(true);
                }
            }
        });
    }

    function ajaxSubmit(obj) {
        var url = $(obj).attr('action') || window.location.href;
        var callback_name = $(obj).attr('callback');
        var callback = window[callback_name];
        // eval("callback = " + callback_name + "");

        var data = {};
        $.map($(obj).serializeArray(), function(item) {
            data[item.name] = item.value;
        });
        $.ajax({
            url: url,
            type: 'POST',
            data: data,
            dataType: 'JSON',
            success: function(ret) {
                if (Number(ret.status) === 200) {
                    if (isNotEmpty(callback)) {
                        callback && callback(ret);
                    }
                } else if (ret.status == null) {
                    alert('status is not defined in server response!');
                }
            }
        });
    }

    function ajaxGetSubmit(obj) {
        var url = $(obj).attr('action') || window.location.href;
        var callback_name = $(obj).attr('callback');
        var callback = window[callback_name];
        // eval("callback = " + callback_name + "");
        var data = {};
        $.map($(obj).serializeArray(), function(item) {
            data[item.name] = item.value;
        });
        $.ajax({
            url: url,
            type: 'GET',
            data: data,
            dataType: 'JSON',
            success: function(ret) {
                if (Number(ret.status) === 200) {
                    if (isNotEmpty(callback)) {
                        callback && callback(ret);
                    }
                } else if (ret.status == null) {
                    alert('status is not defined in server response!');
                }
            }
        });
    }

    function get_oid(obj) {
        if (obj.hasOwnProperty('_id')) {
            return obj._id['$oid'];
        }
        return '';
    }

    function set_active_head1(idx) {
        // 首页，我的问卷，问卷库等几个tab的切换
        $('.main-nav li:eq(' + idx + ')').addClass('active');
    }

    function set_active_head_v2(idx) {
        // 新版 首页，我的问卷，问卷库等几个tab的切换
        $('.left_Menu li a').removeClass('active');
        $('.left_Menu li:eq(' + idx + ') a').addClass('active');
    }

    function scroll_to(obj, value) {
        // 滚动滚动条至对象所在的位置
        var is_iframe = !!(self.frameElement && self.frameElement.tagName === 'IFRAME');
        var value1 = value || 0;
        var top = $(obj).offset().top - value1;
        if (is_iframe) {
            get_iframe_height(obj);
        }
        $('body, html').animate(
            {
                scrollTop: top
            },
            'fast'
        );
    }

    // 删除数组中某位置的元素
    Array.prototype.remove = function(from, to) {
        var rest = this.slice((to || from) + 1 || this.length);
        this.length = from < 0 ? this.length + from : from;
        return this.push.apply(this, rest);
    };

    // 确认框

    function jsConfirm(Obj) {
        var onlyid = Obj.onlyid || 'maptss';
        var Tinfo = {
            title: Obj.title || '提示',
            content: Obj.content || "<span style='color:#ef6262;'>确定要删除吗？</span>",
            // 提示内容
            conw: Obj.conw || 300,
            // 宽度
            obj: Obj.obj || false,
            // 执行方法
            Param: Obj.Param || '',
            // 执行方法参数
            obj_text: Obj.obj_text || '确定',
            // 执行方法按钮内容
            close_obj: Obj.close_obj || false,
            // 取消方法
            close_Param: Obj.close_Param || '',
            // 取消方法参数
            close_text: Obj.close_text || '取消',
            // 取消方法按钮内容
            is_zhifu: false
        };
        var qr = '<div class="WJButton wj_blue tcQz">' + Tinfo.obj_text + '</div>';
        var qx = '<div class="WJButton wj_blue uniteC">' + Tinfo.close_text + '</div>';
        var con =
            '<div class="tccCon">' +
            '<div class="tccCon_t">' +
            Tinfo.content +
            '</div><div class="tccCon_a">' +
            qr +
            qx +
            '</div></div>';

        // 创建弹出层
        new jsbox({
            onlyid: onlyid,
            title: Tinfo.title,
            conw: Tinfo.conw,
            // FixedTop:170,
            content: con,
            range: true,
            mack: true
        }).show();

        // 确定事件
        $('.tcQz')
            .die()
            .live('click', function() {
                var isReturn = Tinfo.obj(Tinfo.Param);
                if (isReturn === undefined || isReturn == null) {
                    $('.jsbox_close').click();
                    setTimeout(function() {
                        $('.zon_edit').remove();
                    }, 100);
                }
            });
        // 取消事件
        $('.uniteC').one('click', function() {
            if (Tinfo.close_obj) {
                Tinfo.close_obj(Tinfo.close_Param);
            }
            $('.jsbox_close').click();
        });
        // 关闭按钮取消事件
        $('.jsbox_close').one('mousedown', function() {
            if (Tinfo.close_obj) {
                Tinfo.close_obj(Tinfo.close_Param);
            }
            $('.jsbox_close').click();
            return false;
        });
    }

    function jsCropConfirm(Obj) {
        var Tinfo = {
            title: Obj.title || '提示',
            content: Obj.content || '确定要删除吗？',
            // 提示内容
            conw: Obj.conw || 300,
            // 宽度
            obj: Obj.obj || false,
            // 执行方法
            Param: Obj.Param || '',
            // 执行方法参数
            obj_text: Obj.obj_text || '确定',
            // 执行方法按钮内容
            close_obj: Obj.close_obj || false,
            // 取消方法
            close_Param: Obj.close_Param || '',
            // 取消方法参数
            close_text: Obj.close_text || '取消'
            // 取消方法按钮内容
        };
        var qr = '<div class="WJButton wj_blue tcQz">' + Tinfo.obj_text + '</div>';
        var qx = '<div class="WJButton wj_blue c_close">' + Tinfo.close_text + '</div>';
        var con =
            '<div class="tccCon">' +
            '<div class="tccCon_t">' +
            Tinfo.content +
            '</div><div class="tccCon_a">' +
            qr +
            qx +
            '</div></div>';

        // 创建弹出层
        var params = {
            onlyid: 'maptss',
            title: Tinfo.title,
            conw: Tinfo.conw,
            // FixedTop:170,
            content: con,
            range: true,
            mack: true
        };
        Obj.editorName ? (params.onlyid += Obj.editorName) : params.onlyid;
        new jsbox(params).show();
        // 确定事件
        $('.tcQz')
            .die()
            .live('click', function() {
                var isReturn = Tinfo.obj(Tinfo.Param);
                if (isReturn === undefined || isReturn == null) {
                    $('.jsbox_close').click();
                    setTimeout(function() {
                        $('.zon_edit').remove();
                    }, 100);
                }
            });
        $('.c_close').bind('click', function() {
            if (Tinfo.close_obj) {
                Tinfo.close_obj(Tinfo.close_Param);
            }
            $('.jsbox_close').click();
        });
        // 关闭按钮取消事件
        $('.jsbox_close').one('mousedown', function() {
            $('.jsbox_close').click();
            return false;
        });
    }

    function sleep(delay) {
        var start = new Date().getTime();
        while (new Date().getTime() < start + delay);
    }

    if (!Array.prototype.filter) {
        Array.prototype.filter = function(fun /*, thisp*/) {
            'use strict';

            if (this == null) throw new TypeError();

            var t = Object(this);
            var len = t.length >>> 0;
            if (typeof fun !== 'function') throw new TypeError();

            var res = [];
            var thisp = arguments[1];
            for (var i = 0; i < len; i++) {
                if (i in t) {
                    var val = t[i]; // in case fun mutates this
                    if (fun.call(thisp, val, i, t)) res.push(val);
                }
            }

            return res;
        };
    }

    // 数组去重
    Array.prototype.unique = function() {
        var n = []; // 一个新的临时数组
        for (var i = 0; i < this.length; i++) {
            // 遍历当前数组
            if (n.indexOf(this[i]) === -1) n.push(this[i]);
        }
        return n;
    };

    if (!Array.prototype.includes) {
        Array.prototype.includes = function(searchElement, fromIndex) {
            if (this == null) {
                throw new TypeError('"this" is null or not defined');
            }
            var o = Object(this);
            var len = o.length >>> 0;
            if (len === 0) {
                return false;
            }
            var n = fromIndex | 0;
            var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
            while (k < len) {
                if (o[k] === searchElement) {
                    return true;
                }
                k++;
            }
            return false;
        };
    }

    // 确认框
    function jsAlert(Obj) {
        var onlyid = Obj.onlyid || 'maptss';
        var Tinfo = {
            title: Obj.title || '提示',
            content: Obj.content || '确定要删除吗？',
            // 提示内容
            conw: Obj.conw || 300,
            // 宽度
            obj: Obj.obj || false,
            // 执行方法
            Param: Obj.Param || '',
            // 执行方法参数
            obj_text: Obj.obj_text || '确定'
            // 执行方法按钮内容
        };
        var qr = '<div class="WJButton wj_blue tcQz">' + Tinfo.obj_text + '</div>';
        var con =
            '<div class="tccCon">' +
            '<div class="tccCon_t">' +
            Tinfo.content +
            '</div><div class="tccCon_a">' +
            qr +
            '</div></div>';

        // 创建弹出层
        new jsbox({
            onlyid: onlyid,
            title: Tinfo.title,
            conw: Tinfo.conw,
            // FixedTop:170,
            content: con,
            Close: false,
            range: true,
            mack: true
        }).show();

        // 确定事件
        $('.tcQz')
            .die()
            .live('click', function() {
                if (Tinfo.obj) {
                    var isReturn = Tinfo.obj(Tinfo.Param);
                    if (isReturn === undefined || isReturn == null) {
                        $('.jsbox_close', '#' + onlyid).click();
                    }
                } else {
                    $('.jsbox_close', '#' + onlyid).click();
                }
            });
        // 确定事件，跳转链接
        $('.new_tcQz')
            .die()
            .live('click', function() {
                var pid = $(this).attr('pid');
                if (Tinfo.obj) {
                    var isReturn = Tinfo.obj(Tinfo.Param);
                    if (isReturn === undefined || isReturn == null) {
                        window.location.href = '/edit/survey/' + pid;
                    }
                } else {
                    window.location.href = '/edit/survey/' + pid;
                }
            });
    }

    function InterceptString(str, length, length1) {
        // str=str.replace(/[" "|"　"]/g,"");//去半角+全角空格
        // str=str.replace(/\s+/g,"");//去半角空格
        // str=str.replace(/[\u3000]/g,"")去全角空格
        // str=str.replace(/\s/ig,'');去半角空格
        if (str.length > length) {
            if (length1 === 0) {
                length1 = length;
            }
            if (str.length >= length1) {
                var str_left = str.substr(0, length1);
                var str_right = str.substr(length1);
                var banjiao = 0;
                var quanjiao = 0;
                var strCode;
                for (var i = 0; i < str_left.length; i++) {
                    strCode = str.charCodeAt(i);

                    if (strCode >= 33 && strCode <= 126) {
                        banjiao++;
                    } else {
                        quanjiao++;
                    }
                }
                if (quanjiao + banjiao / 2 > length || quanjiao + banjiao / 2 - length === 0.5) {
                    str_left = str_left.substr(0, str_left.length - 1);
                    return str_left;
                } else if (quanjiao + banjiao / 2 - length !== 0) {
                    if (length1 + 1 <= str.length) {
                        str_left = InterceptString(str, length, length1 + 1);
                    }
                }
                return str_left;
            }
        }
    }

    function getDaysInOneMonth(year, month) {
        var d = new Date(year, month, 0);
        return d.getDate();
    }
    var developer = 'CC,JJ,PP,SF';

    function get_iframe_height(obj) {
        var top = 0;
        if (isNotEmpty(obj) && obj === -2) {
            top = -2;
        } else if (!isNotEmpty(obj)) {
            top = -1;
        } else {
            top = $(obj).offset().top;
        }
        var body_height = $('body').height() + 30;
        var postObj = body_height + ',' + top;
        if (typeof postMessage !== 'undefined') {
            window.parent.postMessage(postObj, '*');
        }
    }
    // Load页面
    function Appload(Obj) {
        var url = Obj.url || '/';
        if (url.indexOf('?') === -1) {
            url = url + '?rd=' + new Date().getTime();
        } else {
            url = url + '&rd=' + new Date().getTime();
        }
        var Tinfo = {
            obj: Obj.obj || $('body'),
            url: url,
            data: Obj.data || '',
            limg: Obj.limg || false,
            callback: Obj.callback || function() {}
        };
        Tinfo.obj.load(Tinfo.url, Tinfo.data, function() {
            Tinfo.callback();
        });
    }

    String.prototype.replaceAll = function(stringToFind, stringToReplace) {
        var temp = this;
        var index = temp.indexOf(stringToFind);
        while (index !== -1) {
            if (stringToReplace.indexOf(stringToFind) > -1) {
                stringToReplace = stringToReplace.split(stringToFind).join('');
            }
            temp = temp.replace(stringToFind, stringToReplace);
            index = temp.indexOf(stringToFind);
        }
        return temp;
    };

    function edit_lock_alert() {
        $('.loadCon,.loadMack').remove();
        jsConfirm({
            content: '问卷内容刚在其它浏览器窗口被修改， 是否重新加载进行编辑？',
            title: '提示',
            obj_text: '是',
            close_text: '否',
            obj: window.get_edit_lock,
            close_obj: window.close_window
        });
    }

    // 让IE8以下浏览器支持split
    var split;

    // Avoid running twice; that would break the `nativeSplit` reference
    split =
        split ||
        (function(undef) {
            var nativeSplit = String.prototype.split;
            var compliantExecNpcg = /()??/.exec('')[1] === undef; // NPCG: nonparticipating capturing group
            var self;

            self = function(str, separator, limit) {
                // If `separator` is not a regex, use `nativeSplit`
                if (Object.prototype.toString.call(separator) !== '[object RegExp]') {
                    return nativeSplit.call(str, separator, limit);
                }
                var output = [];
                var flags =
                    (separator.ignoreCase ? 'i' : '') +
                    (separator.multiline ? 'm' : '') +
                    (separator.extended ? 'x' : '') + // Proposed for ES6
                    (separator.sticky ? 'y' : ''); // Firefox 3+
                var lastLastIndex = 0;
                // Make `global` and avoid `lastIndex` issues by working with a copy
                separator = new RegExp(separator.source, flags + 'g');
                var separator2;
                var match;
                var lastIndex;
                var lastLength;
                str += ''; // Type-convert
                if (!compliantExecNpcg) {
                    // Doesn't need flags gy, but they don't hurt
                    separator2 = new RegExp('^' + separator.source + '$(?!\\s)', flags);
                }
                /* Values for `limit`, per the spec:
                 * If undefined: 4294967295 // Math.pow(2, 32) - 1
                 * If 0, Infinity, or NaN: 0
                 * If positive number: limit = Math.floor(limit); if (limit > 4294967295) limit -= 4294967296;
                 * If negative number: 4294967296 - Math.floor(Math.abs(limit))
                 * If other: Type-convert, then use the above rules
                 */
                limit =
                    limit === undef
                        ? -1 >>> 0 // Math.pow(2, 32) - 1
                        : limit >>> 0; // ToUint32(limit)
                while ((match = separator.exec(str))) {
                    // `separator.lastIndex` is not reliable cross-browser
                    lastIndex = match.index + match[0].length;
                    if (lastIndex > lastLastIndex) {
                        output.push(str.slice(lastLastIndex, match.index));
                        // Fix browsers whose `exec` methods don't consistently return `undefined` for
                        // nonparticipating capturing groups
                        if (!compliantExecNpcg && match.length > 1) {
                            match[0].replace(separator2, function() {
                                for (var i = 1; i < arguments.length - 2; i++) {
                                    if (arguments[i] === undef) {
                                        match[i] = undef;
                                    }
                                }
                            });
                        }
                        if (match.length > 1 && match.index < str.length) {
                            Array.prototype.push.apply(output, match.slice(1));
                        }
                        lastLength = match[0].length;
                        lastLastIndex = lastIndex;
                        if (output.length >= limit) {
                            break;
                        }
                    }
                    if (separator.lastIndex === match.index) {
                        separator.lastIndex++; // Avoid an infinite loop
                    }
                }
                if (lastLastIndex === str.length) {
                    if (lastLength || !separator.test('')) {
                        output.push('');
                    }
                } else {
                    output.push(str.slice(lastLastIndex));
                }
                return output.length > limit ? output.slice(0, limit) : output;
            };

            // For convenience
            String.prototype.split = function(separator, limit) {
                return self(this, separator, limit);
            };

            return self;
        })();

    function getQueryString(name, isUnescape) {
        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
        var r = window.location.search.substr(1).match(reg);
        if (r != null) {
            if (isUnescape) return r[2];
            return unescape(r[2]);
        }
        return null;
    }

    // 实时保存提示
    function SavePrompt(isOff, message) {
        var message1 = '已实时保存';
        var message2 = '正实时保存';
        if (message) {
            message1 = message2 = message;
        }
        var Sav = $('.SavePrompt');
        if (!isOff) {
            var isOff = false;
        }
        if (isOff) {
            $('.SavePrompt').text(message1);
            setTimeout(function() {
                Sav.fadeOut('slow');
                setTimeout(function() {
                    Sav.remove();
                }, 600);
            }, 800);
        } else {
            if (Sav.length < 1 && !$('.jsbox').is(':visible')) {
                $('body').append('<div class="SavePrompt">正实时保存</div>');
            }
        }
    }

    function notify(className, message, time, func) {
        var f = function() {};
        func = func || f;
        $('body').append('<div class="' + className + '"></div>');
        var $selector = $('.' + className);
        $selector.text(message);
        setTimeout(function() {
            $selector.remove();
            func();
        }, time);
    }

    // 文件上传基础方法
    function file_upload_custom(f, obj, url, success_callback, fail_callback) {
        if (!success_callback) {
            success_callback = function() {};
        }
        if (!fail_callback) {
            fail_callback = function() {};
        }

        var xhr = new XMLHttpRequest();
        xhr.open('POST', url, true);
        var formData;
        formData = new FormData();
        formData.append('file', f);
        for (var key in obj) {
            formData.append(key, obj[key]);
        }
        xhr.onreadystatechange = function(response) {
            if (xhr.readyState === 4 && xhr.status === 200 && xhr.responseText !== '') {
                var ret = JSON.parse(xhr.responseText);
                success_callback(ret, qid);
            } else if (xhr.status !== 200 && xhr.responseText) {
                var ret = JSON.parse(xhr.responseText);
                fail_callback(ret, qid);
            }
        };
        xhr.send(formData);
    }

    function strip_tags(dirtyString) {
        var container = document.createElement('div');
        container.innerHTML = dirtyString;
        return container.textContent || container.innerText;
    }

    if (typeof Array.prototype.reduce !== 'function') {
        Array.prototype.reduce = function(callback, opt_initialValue) {
            if (this === null || typeof this === 'undefined') {
                // At the moment all modern browsers, that support strict mode, have
                // native implementation of Array.prototype.reduce. For instance, IE8
                // does not support strict mode, so this check is actually useless.
                throw new TypeError('Array.prototype.reduce called on null or undefined');
            }
            if (typeof callback !== 'function') {
                throw new TypeError(callback + ' is not a function');
            }
            var index;
            var value;
            var length = this.length >>> 0;
            var isValueSet = false;
            if (arguments.length > 1) {
                value = opt_initialValue;
                isValueSet = true;
            }
            for (index = 0; length > index; ++index) {
                if (this.hasOwnProperty(index)) {
                    if (isValueSet) {
                        value = callback(value, this[index], index, this);
                    } else {
                        value = this[index];
                        isValueSet = true;
                    }
                }
            }
            if (!isValueSet) {
                throw new TypeError('Reduce of empty array with no initial value');
            }
            return value;
        };
    }

    if (!Array.prototype.forEach) {
        Array.prototype.forEach = function(callback, thisArg) {
            var T, k;
            if (this == null) {
                throw new TypeError(' this is null or not defined');
            }
            var O = Object(this);
            var len = O.length >>> 0;
            if (typeof callback !== 'function') {
                throw new TypeError(callback + ' is not a function');
            }
            if (arguments.length > 1) {
                T = thisArg;
            }
            k = 0;
            while (k < len) {
                var kValue;
                if (k in O) {
                    kValue = O[k];
                    callback.call(T, kValue, k, O);
                }
                k++;
            }
        };
    }
    // IE木有flat函数..
    if (!Array.prototype.flat) {
        Array.prototype.flat = function() {
            var result = [];
            var arr = this;
            var fn = function(ary) {
                for (var i = 0; i < ary.length; i++) {
                    var item = ary[i];
                    if (Array.isArray(ary[i])) {
                        fn(item);
                    } else {
                        result.push(item);
                    }
                }
            };
            fn(arr);

            return result;
        };
    }

    function escapeHTML(html) {
        return html.replace(/[<>&"]/g, function(c) {
            return {
                '<': '&lt;',
                '>': '&gt;',
                '&': '&amp;',
                '"': '&quot;'
            }[c];
        });
    }

    function unescapeHTML(a) {
        a = '' + a;
        var html = a
            .replace(/&lt;/g, '<')
            .replace(/&gt;/g, '>')
            .replace(/&amp;/g, '&')
            .replace(/&quot;/g, '"')
            .replace(/&apos;/g, "'");
        return html;
    }

    // 去掉所有html标签
    function delete_html_tag(value) {
        var re = new RegExp('<[^>]*>', 'g'); // 去除所有标签
        value = value.replace(re, '');
        return value;
    }

    /**
     *
     * @param {string} html 目标html
     * @param {string} tagName 要替换的标签
     * @param {string|number} tagTxt 标签要替换的文案
     */
    function replaceHtmlTag(html, tagName, tagTxt) {
        var re = new RegExp('<' + tagName + '[^>]*>', 'g');
        html = html.replace(re, tagTxt);
        return html;
    }

    function escape_html(s) {
        return s
            ? jQuery('<p>')
                  .text(s)
                  .html()
            : '';
    }
    // 兼容IE9以下不支持Object.keys
    if (!Object.keys) {
        Object.keys = function(o) {
            if (o !== Object(o)) {
                throw new TypeError('Object.keys called on a non-object');
            }
            var k = [];
            var p;
            for (p in o) {
                if (Object.prototype.hasOwnProperty.call(o, p)) k.push(p);
            }
            return k;
        };
    }

    var projectPublishFun = {
        init: function(pid, option) {
            this.bState = true; // 默认可发送验证码
            this.setting = {
                pid: pid,
                type: '问卷', // 问卷类型（问卷、表单、测评）
                surveyTitle: '', // 问卷标题
                surveyTotalTitle: '', // 完整问卷标题
                showShare: true, // 当前页面默认是否可以共享模版（概况页、列表页默认不共享）
                page: '', // 当前所在页面
                isPublish: true, // 是否发布
                // publishSaveFun: function(){},  // 确认发布回调函数
                publishCancelFun: function() {} // 取消发布回掉函数
            };
            $.extend(this.setting, option);
            this.validateFun(pid);
        },
        // 验证企业协作权限
        validateFun: function(pid) {
            var _this = this;
            $.ajax({
                url:
                    '/enterprise/check_member_permission/?permission_type=collect&project_id=' +
                    pid,
                type: 'GET',
                dataType: 'json',
                success: function(ret) {
                    if (ret.status === 200) {
                        if (ret.code === 1) {
                            // 收集页面，停止收集
                            if (!_this.setting.isPublish) {
                                _this.checkPconvertForm(pid);
                            } else {
                                // 编辑页面，移除错误提示信息
                                if (
                                    _this.setting.page === 'surveyEdit' ||
                                    _this.setting.page === 'formEdit' ||
                                    _this.setting.page === 'edit_v2'
                                ) {
                                    $('.question').each(function() {
                                        window.verify_question_option.hide($(this).attr('oid'));
                                    });
                                    _this.publishCheckFun(pid);
                                } else if (_this.setting.page === 'assessEdit') {
                                    if (window.is_validate_all()) _this.publishCheckFun(pid);
                                } else {
                                    _this.publishCheckFun(pid);
                                }
                            }
                        } else if (ret.code === 2) {
                            window.loadMack({
                                off: 'on',
                                Limg: 1,
                                text: '您没有权限使用，请联系项目所有者',
                                set: 1000
                            });
                            _this.setting.publishCancelFun();
                        }
                    } else {
                        window.check_permission = false;
                        window.loadMack({
                            off: 'on',
                            Limg: 1,
                            text: '请稍后再试',
                            set: 1000
                        });
                        _this.setting.publishCancelFun();
                    }
                }
            });
        },
        // 判断是否有未编辑完成的题目
        publishCheckFun: function(pid) {
            var _this = this;
            $.ajax({
                url: '/edit/ajax/publish_check/' + pid + '/',
                dataType: 'JSON',
                success: function(ret) {
                    if (ret.err_code) {
                        var errorText = getErrorCodeText(ret.err_code);
                        jsAlert({
                            onlyid: 'assess_score_overstep_popup',
                            title: ' ',
                            content: errorText,
                            range: true,
                            mack: true,
                            obj: function() {
                                $(
                                    '#assess_score_overstep_popup,.assess_score_overstep_popup_lightBox'
                                ).remove();
                            }
                        });
                        return;
                    }
                    if (ret.project_scene === 8 && !ret.has_appraise) {
                        // 360
                        appraiseCheckPop(pid);
                        return;
                    }
                    var invalid_qid_list = ret.invalid_qid_list;
                    var real2fake_id_map = ret.real2fake_id_map;
                    var invalidQidList = [];
                    var errMsgObj = ret.err_msg;
                    _this.hasLocalMedia = ret.need_sign_agreement;
                    if (window.QUESTION_DICT) {
                        // 后端返回realId, 前端映射成本地可用的id
                        invalid_qid_list.forEach(function(qid) {
                            var question = QUESTION_DICT[qid];
                            if (question) {
                                invalidQidList.push(qid);
                            } else {
                                var fakeId = real2fake_id_map[qid];
                                if (fakeId) {
                                    question = QUESTION_DICT[fakeId];
                                    if (question) {
                                        invalidQidList.push(fakeId);

                                        if (errMsgObj[qid]) {
                                            errMsgObj[fakeId] = errMsgObj[qid];
                                            delete errMsgObj[qid];
                                        }
                                    }
                                }
                            }
                        });
                        ret.invalid_qid_list = invalidQidList;
                    }
                    _this.publishCheckCallback(_this, pid, ret);
                }
            });
        },
        publishCheckCallback: function(_this, pid, data) {
            if (
                data.invalid_qid_list.length != 0 ||
                (isBeyongLimit(_this.setting.surveyTotalTitle, 200) &&
                    _this.setting.page === 'edit_v2')
            ) {
                // 未编辑完成的题目
                if (
                    _this.setting.page === 'surveyEdit' ||
                    _this.setting.page === 'formEdit' ||
                    _this.setting.page === 'assessEdit' ||
                    _this.setting.page === 'edit_v2'
                ) {
                    // 如果在预览页，先关闭预览弹窗
                    var $exitPreview = $('.exit_preview');
                    if ($exitPreview.length > 0) {
                        $('.exit_preview').click();
                    }
                    // 验证标题限制200
                    if (isBeyongLimit(_this.setting.surveyTotalTitle, 200)) {
                        if ($('.survey_main>.edit_type_error').length === 0) {
                            $(
                                '<div class="edit_type_error">标题字数不得大于200字</div>'
                            ).insertBefore($('.survey_prefix_wrap'));
                        }
                        scroll_to($('.survey_main_wrap'), $('.edit-center').height());
                    }
                    // 编辑页面，验证项目中是否有未编辑完成的题目，添加提示
                    for (var i = 0; i < data.invalid_qid_list.length; i++) {
                        var qid = data.invalid_qid_list[i];
                        var msg = data.err_msg[qid];
                        if (msg) {
                            verify_question_option.show(qid, msg);
                        } else {
                            var qmodel = get_qmodel(qid);
                            qmodel.show_edit_error_msg();
                        }
                        if (!isBeyongLimit(_this.setting.surveyTotalTitle, 200)) {
                            scroll_to(
                                $('.question[oid=' + data.invalid_qid_list[0] + ']'),
                                $('.edit-center').height()
                            );
                        }
                    }
                } else {
                    // 收集页、数据报表、列表页、概览页，包含未编辑完成的题目
                    var contentObj = {
                        head: {
                            inner: '修改提示',
                            class: 'publish-head'
                        },
                        content: {
                            inner:
                                '<p>该' +
                                _this.setting.type +
                                '包含未编辑完成的题目，暂时无法发布，请先前往编辑页面完成编辑。</p>',
                            class: 'publish-cot'
                        }
                    };
                    confirmationPop(contentObj, function() {
                        window.location.href = '/edit/survey/' + pid;
                    });
                }
            } else {
                if (_this.hasLocalMedia) {
                    _this.setting.openQHearingDialog(_this, data);
                    return;
                }
                if (_this.setting.hasMobile) {
                    var hitThreshold = data.hit_threshold; // 0:没有触发,1:触发创建阈值,2:触发发布阈值,4:已通过手机号码验证
                    var thresholdArr = [1, 2];
                    if (thresholdArr.includes(hitThreshold)) {
                        // 触发创建,发布阈值
                        _this.showValidatePhoneFun(pid, data);
                    } else {
                        _this.publishFun(pid, data.super_account, data.ad_switch);
                    }
                } else {
                    var is_relation_project = true;
                    _this.showBindMobileFun(
                        is_relation_project,
                        pid,
                        data.super_account,
                        data.ad_switch
                    );
                }
            }
        },
        // 发布阈值-手机验证弹窗
        showValidatePhoneFun: function(pid, data) {
            var _this = this;
            var mobile = _this.setting.mobile;
            var content =
                '<p>为了您的账号隐私安全，需要进行此次验证</p>' +
                '<p>绑定验证：' +
                hide_mobile(mobile) +
                '</p>' +
                '<p class="code-text">验证码</p>' +
                '<div class="mobile-code-wrap">' +
                '<input type="text" autocomplete="off" class="code" maxlength="6" placeholder="请输入" />' +
                '<span class="get-code-button">发送验证码</span>' +
                '<div class="error-tips"></div>' +
                '</div>';
            var contentObj = {
                head: {
                    inner: '手机验证',
                    class: 'publish-head'
                },
                content: {
                    inner: content,
                    class: 'validate-phone'
                },
                params: {
                    type: 'validatePhone',
                    pid: pid,
                    data: data
                },
                popupWrapClass: 'validate-phone-wrap'
            };
            confirmationPop(contentObj, function() {});
            this.sendVcodeFun(mobile);
            var $popup = $('.validate-phone-wrap');
            $popup.find('.popup_btn_right').addClass('disabled');
            // 获取验证码
            $popup.find('.get-code-button').click(function() {
                _this.sendVcodeFun(mobile);
            });
            $popup.on(
                {
                    input: function() {
                        var phoneCode = $(this)
                            .val()
                            .replace(/[^\d]/g, '');
                        $(this).val(phoneCode);
                        if ($(this).val().length == 6) {
                            _this.securityCheckFun(pid, data);
                        }
                    },
                    blur: function() {
                        if ($(this).val().length != 6) {
                            $popup.find('.popup_btn_right').addClass('disabled');
                            var $errorTips = $popup.find('.error-tips');
                            $errorTips.html('请输入6位数字的验证码');
                            return;
                        }
                        // _this.securityCheckFun(pid, data);
                    }
                },
                '.code'
            );
        },
        // 发布阈值-获取验证码
        sendVcodeFun: function(mobile) {
            if (!mobile) {
                loadMarkFun('手机号码有误，请刷新后重试！');
                return;
            }
            var $popup = $('.validate-phone-wrap');
            var $codeBtn = $popup.find('.get-code-button');
            if ($codeBtn.hasClass('btn_disabled') || !this.bState) return;
            var $errorTips = $popup.find('.error-tips');
            var $input = $popup.find('.code');
            $errorTips.html('');
            $input.val('');
            $input.focus();
            $popup.find('.popup_btn_right').addClass('disabled');
            var url = '/auth/api/mobile_validatecode?mobile=' + mobile + '&action=security';
            var _this = this;
            ajaxGet(url, function(res) {
                var errCode = res.err_code;
                if (errCode) {
                    loadMarkFun(getCodeErrMsg(errCode));
                    return;
                }
                _this.getMobileCode($codeBtn);
            });
        },
        // 发布阈值-手机号码验证
        validatePhoneFun: function(pid, data) {
            var $popup = $('.validate-phone-wrap');
            var phoneCode = $popup.find('.code').val();
            if (phoneCode.length != 6) {
                $popup.find('.popup_btn_right').addClass('disabled');
                var $errorTips = $popup.find('.error-tips');
                $errorTips.html('请输入6位数字的验证码');
                return false;
            }
            this.securityCheckFun(pid, data, 'btnValidate');
        },
        // 验证手机号
        securityCheckFun: function(pid, data, from) {
            var _this = this;
            var mobile = this.setting.mobile;
            var $popup = $('.validate-phone-wrap');
            var vcode = $popup.find('.code').val();
            var url = '/auth/api/security_check/?mobile=' + mobile + '&vcode=' + vcode;
            ajaxGet(url, function(res) {
                var errCode = res.err_code;
                var errMsg = res.err_msg;
                var $errorTips = $popup.find('.error-tips');
                var $rightBtn = $popup.find('.popup_btn_right');
                if (errCode) {
                    $errorTips.html(errMsg);
                    $rightBtn.addClass('disabled');
                    return;
                }
                $errorTips.html('');
                $rightBtn.removeClass('disabled');
                if (from === 'btnValidate') {
                    // 确定按钮校验通过关闭弹窗，失焦校验通过不关闭弹窗
                    // 只移除手机验证弹窗的内容.如销毁弹窗,在弹出发布弹窗时,页面会有瞬间没有阴影的闪动
                    $('.popup_box .confirm_popup_box').remove();
                    _this.publishFun(pid, data.super_account, data.ad_switch);
                }
            });
        },
        // 发布问卷弹窗
        publishFun: function(pid, is_super, is_on) {
            var _this = this;
            var content = '';
            if (_this.setting.isPublish) {
                if (_this.setting.surveyTitle) {
                    content =
                        '<p>你要发布' +
                        _this.setting.type +
                        '<span>《' +
                        _this.setting.surveyTitle +
                        '》</span>吗？</p>';
                } else {
                    content = '<p>是否发布' + _this.setting.type + '？</p>';
                }
            }
            // 仅当考试/测评类型，打开考试付费开关，短信余额为0时才触发
            if (
                _this.setting.pType === 2 &&
                Boolean(_this.setting.prepaidSwitch) &&
                _this.setting.smsQuota <= 0
            ) {
                content +=
                    '<p style="margin-top: 5px; margin-bottom: 10px; font-size: 13px;">' +
                    '<span>当前可用短信余额为：0，无法进行答卷收集；建议</span>' +
                    '<a style="color: #2672ff; display: inline-block;" href="/member/buysms?direct-back=true">购买短信</span>' +
                    '</p>';
            }

            if (is_super) {
                content +=
                    '<div class="luckdraw_temp"><label class="w-checkbox"><input style="vertical-align:middle;margin:-2px 6px 0 0 !important;" type="checkbox" id="luckdraw_selector" ' +
                    (is_on === 'on' ? 'checked' : '') +
                    '/><span class="w-icon w-no-active w-checkbox-icon"></span>启用默认抽奖游戏，提高收集效率</label></div>';
            }

            if (
                _this.setting.showShare &&
                _this.setting.isPublish &&
                _this.setting.sceneType !== 'school'
            ) {
                var shareUnChecked;
                if (_this.setting.hasPublished === 'true') {
                    shareUnChecked = true;
                } else {
                    shareUnChecked = Boolean(localStorage.getItem('share_unchecked_' + pid));
                }

                content +=
                    '<label class="w-checkbox share-lib"><input style="vertical-align:middle;margin:-2px 6px 0 0 !important;" type="checkbox" ' +
                    (shareUnChecked ? '' : 'checked') +
                    ' id="checkbox_selector"/><span class="w-icon w-no-active w-checkbox-icon"></span>允许共享为模板</label><i class="tips" title="选中该选项，本' +
                    _this.setting.type +
                    '经审核合格后会添加到模板库中，供其他会员制作' +
                    _this.setting.type +
                    '时参考。"></i>';
            }
            var contentObj = {
                head: {
                    inner: '发布确认',
                    class: 'publish-head'
                },
                content: {
                    inner: content,
                    class: 'publish-cot'
                }
            };
            confirmationPop(contentObj, function() {
                showCaptchaUtils(function(data) {
                    if (data.status === 'success') {
                        _this.publishSaveFun(_this.setting, data.data || {});
                    }
                });
            });
        },
        // 显示绑定手机号弹窗
        showBindMobileFun: function(is_relation_project, pid, is_super, is_on, hasThis) {
            var _this;
            hasThis ? (_this = hasThis) : (_this = this);
            var shareContent = '';
            var luckdrawContent = '';
            var str = '';
            var error_str = '';
            if (is_relation_project === true) {
                str = '确定并发布' + _this.setting.type + '';
                error_str = '据网信办规定，发布' + _this.setting.type + '需绑定手机';
                if (_this.setting.showShare && _this.setting.isPublish) {
                    var shareUnChecked = localStorage.getItem('share_unchecked_' + pid);
                    if (shareUnChecked) {
                        shareContent =
                            '<div class="share_temp"><label><input type="checkbox" id="checkbox_selector" />' +
                            _this.setting.type +
                            '共享到模版库</label></div>';
                    } else {
                        shareContent =
                            '<div class="share_temp"><label><input type="checkbox" id="checkbox_selector" checked />' +
                            _this.setting.type +
                            '共享到模版库</label></div>';
                    }
                    if (is_super) {
                        luckdrawContent =
                            '<div class="luckdraw_temp"><label><input style="margin-right:2px !important;" type="checkbox" id="luckdraw_selector" ' +
                            (is_on === 'on' ? 'checked' : '') +
                            '/> 启用默认抽奖游戏，提高收集效率</label></div>';
                    }
                }
            } else {
                error_str = '';
                var moneyPages = ['recharge', 'buySMS', 'buyEmail', 'buyVip', 'redEnvelope'];
                if (moneyPages.indexOf(is_relation_project) >= 0) {
                    error_str = '涉及资金安全，请先绑定手机号';
                }
                str = '确定';
            }
            var bindMobileHtml =
                '' +
                '<div class="bind_mobile_wrap">' +
                '<div class="bind_mobile_form">' +
                '<div class="form_item_wrap">' +
                '<div class="form_item form_mobile"><label for=""><input type="text" placeholder="手机号" name="mobile" class="mobile" /></label></div>' +
                '<div class="form_error">' +
                error_str +
                '</div>' +
                '</div>' +
                '<div class="form_item_wrap">' +
                '<div class="form_item form_vcode"><label for=""><input type="text" placeholder="验证码" name="vcode" class="vcode" /></label><a class="btn_get_vcode">获取验证码</a></div>' +
                '<div class="form_error"></div>' +
                '</div>' +
                '</div>' +
                luckdrawContent +
                shareContent +
                '<div class="btn_wrap"><a class="btn_publish btn_disable">' +
                str +
                '</a></div>' +
                '</div>';
            new jsbox({
                onlyid: 'publish_bind_mobile',
                title: '绑定手机号',
                content: bindMobileHtml,
                conw: 600,
                range: true,
                mack: true
            }).show();

            // 关闭按钮
            $('#publish_bind_mobile .jsbox_close').one('click', function() {
                if (_this.setting.publishCancelFun) {
                    _this.setting.publishCancelFun();
                }
            });
            // 监听手机号码
            $('#publish_bind_mobile input[name=mobile]').keyup(function(e) {
                var $this = $(this);
                // var mobile = $this.val().replace(/\D/g,'');
                var mobile = $this.val();
                var $mobileError = $this.parents('.form_item_wrap').find('.form_error');
                // mobile = mobile.substr(0, 11);
                $this.val(mobile);
                if (mobile !== '') {
                    $mobileError.text('').hide();
                    if (!idyLoginValidate.mobile(mobile)) {
                        _this.validateMobileAndVcode($this, is_relation_project);
                    }
                } else {
                    if (is_relation_project === true) {
                        $mobileError
                            .show()
                            .text('据网信办规定，发布' + _this.setting.type + '需绑定手机');
                    }
                }
            });
            // 监听验证码
            $('#publish_bind_mobile input[name=vcode]').keyup(function(e) {
                var $this = $(this);
                // var mobile = $this.val().replace(/\D/g,'');
                var vcode = $this.val();
                var $vcodeError = $this.parents('.form_item_wrap').find('.form_error');
                if (vcode.length >= 6) vcode = vcode.substr(0, 6);
                $this.val(vcode);
                if (vcode !== '') {
                    $vcodeError.text('').hide();
                    if (vcode.length === 6) {
                        $this
                            .parents('.bind_mobile_wrap')
                            .find('.btn_publish')
                            .removeClass('btn_disable')
                            .addClass('not_vcode');
                        // _this.validateMobileAndVcode($this);
                    } else {
                        $this
                            .parents('.bind_mobile_wrap')
                            .find('.btn_publish')
                            .addClass('btn_disable')
                            .addClass('not_vcode');
                    }
                } else {
                    $vcodeError.show().text('请输入验证码');
                }
            });
            // 获取验证码
            $('#publish_bind_mobile .btn_get_vcode').click(function(e) {
                if ($(this).hasClass('btn_disabled')) return;
                var $this = $(this);
                var $mobile = $this.parents('.bind_mobile_form').find('input[name=mobile]');
                var mobile = $mobile.val();
                var $mobileError = $mobile.parents('.form_item_wrap').find('.form_error');
                if (mobile === '') {
                    if (is_relation_project === true) {
                        $mobileError
                            .text('据网信办规定，发布' + _this.setting.type + '需绑定手机')
                            .show();
                    } else {
                        window.loadMack({
                            off: 'on',
                            Limg: 0,
                            text: ' 手机号不能为空',
                            set: 1000
                        });
                    }
                    return false;
                } else if (idyLoginValidate.mobile(mobile)) {
                    var text =
                        '手机号格式有误，如非中国大陆用户<a target="_blank" class="loginHelpURL" style="color:blue!important;text-decoration: underline!important;display: inline!important;" href="' +
                        idyLoginValidate.loginHelpURL +
                        '">请点此<a>';
                    $mobileError.html(text).show();
                    return false;
                } else {
                    $mobileError.text('').hide();
                }
                if (_this.bState) {
                    ajaxPost(
                        '/register/auth_mobile_validatecode/',
                        {
                            mobile: mobile,
                            usefor: 'publishproject_bindmobile'
                        },
                        function(response) {
                            if (response.error_msg || response.err_msg) {
                                if (response.error_msg !== '该手机号已被使用') {
                                    window.loadMack({
                                        off: 'on',
                                        Limg: 0,
                                        text: response.error_msg,
                                        set: 2000
                                    });
                                }
                                // if(response.error_msg == '该手机号已被使用'){
                                //     $('.jsbox_close').click();
                                //     var bindedHtml = tplStr.accountConflict.content;
                                //     var bindMobilePopup = new jsbox({
                                //         onlyid: 'havebind_mobile',
                                //         title: tplStr.accountConflict.title,
                                //         content: bindedHtml,
                                //         conw: 600,
                                //         range: true,
                                //         mack: true
                                //     }).show();
                                // }else{
                                //     $mobileError.text(response.error_msg).show();
                                // }
                            } else {
                                window.loadMack({
                                    off: 'on',
                                    Limg: 0,
                                    text: ' 验证码已发送，请查收',
                                    set: 2000
                                });
                                _this.getMobileCode($this);
                            }
                        }
                    );
                }
            });

            $('.third_close').live('click', function() {
                $('.jsbox_close').click();
                $('.loadCon,.loadMack').remove();
            });

            // 账号合并提醒弹窗点击事件
            // 暂不合并按钮
            $('#can_merge_account .not_merge').live('click', function() {
                window._hmt.push(['_trackEvent', '账号合并系列', 'click', '2、暂不合并 点击次数']);
                show_account({
                    flag: false,
                    is_relation_project: is_relation_project
                });
                return;
            });
            account_merge_btn(is_relation_project, pid);
            // 显示更多按钮
            $('#can_merge_account .show_more').live('click', function() {
                $('#can_merge_account .wrap3').addClass('col_black');
                $(this).addClass('col_white');
            });
            // 关闭按钮
            $('#can_merge_account .jsbox_close').live('click', function() {
                window._hmt.push([
                    '_trackEvent',
                    '账号合并系列',
                    'click',
                    '4、合并弹窗关闭 点击次数'
                ]);
            });

            // 确定并发布问卷
            $('#publish_bind_mobile .btn_publish').click(function(e) {
                var $this = $(this);
                if (!$this.hasClass('btn_disable')) {
                    $(this).text('确定中...');
                    if ($this.hasClass('can_merge')) {
                        // 可以进行账号合并
                        var phoneNum = $this.attr('data-mobile');
                        // var phoneNum = '17621961237';
                        show_account({
                            flag: true,
                            phoneNum: phoneNum,
                            is_relation_project: is_relation_project
                        });
                        return;
                    } else if ($this.hasClass('cant_merge')) {
                        show_account({
                            flag: false,
                            is_relation_project: is_relation_project
                        });
                        return;
                    }
                    var $bindMobileForm = $this.parents('.bind_mobile_wrap');
                    var $vcode = $bindMobileForm.find('input[name=vcode]');
                    if (is_relation_project === true) {
                        var $mobile = $bindMobileForm.find('input[name=mobile]');
                        var mobile = $mobile.val();
                        var $mobileError = $mobile.parents('.form_item_wrap').find('.form_error');
                        var vcode = $vcode.val();
                        var $vcodeError = $vcode.parents('.form_item_wrap').find('.form_error');
                        var is_shared = $('#checkbox_selector').attr('checked');
                        var ad_switch;
                        if ($('#luckdraw_selector').length == 0) {
                            ad_switch = 'on';
                        } else {
                            ad_switch = $('#luckdraw_selector').attr('checked') ? 'on' : 'off';
                        }
                        if (mobile === '') {
                            $mobileError
                                .text('据网信办规定，发布' + _this.setting.type + '需绑定手机')
                                .show();
                            return false;
                        } else if (idyLoginValidate.mobile(mobile)) {
                            var text =
                                '手机号格式有误，如非中国大陆用户<a target="_blank" class="loginHelpURL" href="' +
                                idyLoginValidate.loginHelpURL +
                                '">请点此<a>';
                            $mobileError.text(text).show();
                            return false;
                        } else {
                            $mobileError.text('').hide();
                        }
                        if (vcode === '') {
                            $vcodeError.text('请输入验证码').show();
                            return false;
                        } else {
                            $vcodeError.text('').hide();
                        }
                        if (!is_shared) {
                            localStorage.setItem('share_unchecked_' + pid, true);
                        } else {
                            localStorage.removeItem('share_unchecked_' + pid);
                        }
                        $('.loadMack, .loadCon').remove();
                        window.loadMack({
                            off: 'on',
                            text: '发布中',
                            set: 0
                        });
                        setTimeout(function() {
                            // lodding去除
                            $('.loadCon,.loadMack').remove();
                            window.location.reload();
                        }, 60000);
                        if ($this.hasClass('not_vcode')) {
                            _this.validateMobileAndVcode($vcode, is_relation_project);
                        } else {
                            var data = {
                                mobile: mobile,
                                vcode: vcode,
                                proj_id: pid,
                                status: 1,
                                is_shared: is_shared,
                                ad_switch: ad_switch
                            };
                            ajaxPost(
                                '/edit/ajax/bind_mobile_update_project_status/',
                                data,
                                function(response) {
                                    if (response.error_msg) {
                                        $('.loadMack, .loadCon').remove();
                                        if (response.error_msg.indexOf('手机号') != -1) {
                                            $mobileError.text(response.error_msg).show();
                                            $vcodeError.text('').hide();
                                        } else {
                                            $mobileError.text('').hide();
                                            $vcodeError.text(response.error_msg).show();
                                        }
                                    } else {
                                        if (response.is_dirty === true) {
                                            window.location.href = '/publish/share/' + pid;
                                        } else {
                                            $('.loadMack, .loadCon').remove();
                                            window.loadMack({
                                                off: 'on',
                                                text: '发布成功',
                                                set: 0
                                            });
                                            _this.publishSuccessFun(pid, response);
                                        }
                                    }
                                }
                            );
                        }
                    } else {
                        if ($this.hasClass('not_vcode')) {
                            _this.validateMobileAndVcode($vcode, is_relation_project);
                        }
                    }
                }
            });
        },
        // 验证手机号和验证码
        validateMobileAndVcode: function(obj, is_relation_project) {
            var $bindMobileForm = obj.parents('.bind_mobile_wrap');
            var $mobile = $bindMobileForm.find('input[name=mobile]');
            var mobile = $mobile.val();
            var $mobileError = $mobile.parents('.form_item_wrap').find('.form_error');
            var $vcode = $bindMobileForm.find('input[name=vcode]');
            var vcode = $vcode.val();
            var $vcodeError = $vcode.parents('.form_item_wrap').find('.form_error');
            var $btnPublish = $bindMobileForm.find('.btn_publish');
            var $share = $bindMobileForm.find('.share_temp');
            var $luckdraw = $bindMobileForm.find('.luckdraw_temp');
            console.log($luckdraw);
            if (vcode.length === 6) {
                var data = {
                    mobile: mobile,
                    vcode: vcode,
                    _xsrf: $.cookie('_xsrf')
                };
                $.ajax({
                    url: '/register/mobile_validate/',
                    data: data,
                    dataType: 'JSON',
                    type: 'POST',
                    timeout: 60000,
                    success: function(response) {
                        if (Number(response.status) === 200) {
                            // 先做账号合并的判断
                            if (response.data) {
                                if (response.data.can_merge) {
                                    // 可以进行账号合并
                                    $('#publish_bind_mobile .btn_publish')
                                        .addClass('can_merge')
                                        .attr('data-mobile', response.mobile)
                                        .removeClass('not_vcode')
                                        .click();
                                } else {
                                    // 不可以进行账号合并
                                    $('#publish_bind_mobile .btn_publish')
                                        .addClass('cant_merge')
                                        .removeClass('not_vcode')
                                        .click();
                                }
                                return;
                            }
                            window.current_vcode = data.vcode;
                            if (response.error_msg) {
                                $('.loadMack, .loadCon').remove();
                                if (response.error_msg.indexOf('手机号') !== -1) {
                                    $mobileError.text(response.error_msg).show();
                                    $vcodeError.text('').hide();
                                } else {
                                    $mobileError.text('').hide();
                                    $vcodeError.text(response.error_msg).show();
                                }
                                // $btnPublish.addClass('btn_disable');
                                if ($share) $share.hide();
                                if ($luckdraw) $luckdraw.hide();
                            } else {
                                if (
                                    is_relation_project === true ||
                                    typeof is_relation_project === 'undefined'
                                ) {
                                    $btnPublish.removeClass('not_vcode').click();
                                    if ($share) $share.show();
                                    if ($luckdraw) $luckdraw.show();
                                } else if (
                                    is_relation_project === false ||
                                    is_relation_project == 'addContactGroup' ||
                                    is_relation_project == 'addEmail'
                                ) {
                                    window.loadMack({
                                        off: 'on',
                                        Limg: 0,
                                        text: '绑定成功',
                                        set: 1000
                                    });
                                    location.reload();
                                } else if (is_relation_project === 'cash_withdrawal') {
                                    $('#lightBox').remove();
                                    $('#publish_bind_mobile').remove();
                                    window.cash_reset(mobile);
                                } else if (is_relation_project === 'recharge') {
                                    $('#lightBox').remove();
                                    $('#publish_bind_mobile').remove();
                                    window.showRechargePopup(mobile);
                                } else if (
                                    is_relation_project == 'buySMS' ||
                                    is_relation_project == 'buyEmail' ||
                                    is_relation_project == 'buyVip' ||
                                    is_relation_project == 'createEnt' ||
                                    is_relation_project == 'buySampleService'
                                ) {
                                    var bindMobileCallback = {
                                        buySMS: window.showBuySMSPopup,
                                        buyEmail: window.showBuyEmailPopup,
                                        buyVip: window.buyVipPopup,
                                        createEnt: window.createEntCallback,
                                        buySampleService: window.buySampleServiceCallback
                                    };
                                    var callbackFunc = bindMobileCallback[is_relation_project];
                                    if (callbackFunc) {
                                        $('#lightBox').remove();
                                        $('#publish_bind_mobile').remove();
                                        callbackFunc();
                                    }
                                } else if (is_relation_project == 'bindWechat') {
                                    window.location.href = '/weixin/componentloginpage/';
                                } else if (
                                    is_relation_project == 'redEnvelope' ||
                                    is_relation_project == 'customDomain'
                                ) {
                                    var buttonSelectorDict = {
                                        redEnvelope: '.btn_next',
                                        customDomain: '.btn_audit'
                                    };
                                    var buttonSelector = buttonSelectorDict[is_relation_project];
                                    window.mobileBinded = true;
                                    $('#lightBox').remove();
                                    $('#publish_bind_mobile').remove();
                                    var button = document
                                        .getElementById('plugin_center_iframe')
                                        .contentDocument.querySelector(buttonSelector);
                                    $(button)[0].click();
                                }
                            }
                        }
                    }
                });
            } else {
                $btnPublish.addClass('btn_disable');
                if ($share) $share.hide();
                if ($luckdraw) $luckdraw.hide();
            }
        },
        // 正常流程发布成功的回调函数(已绑定过手机号的用户)
        publishSaveFun: function(param, tecentData) {
            param = param || this.Param;
            var pid = param.pid;
            if (!window.is_shared) {
                localStorage.setItem('share_unchecked_' + pid, true);
            } else {
                localStorage.removeItem('share_unchecked_' + pid);
            }
            var data = $.extend(
                {
                    proj_id: pid,
                    status: 1,
                    is_shared: window.is_shared,
                    _xsrf: $.cookie('_xsrf'),
                    ad_switch: window.ad_switch
                },
                tecentData || {}
            );
            $('.loadMack, .loadCon').remove();
            // 移除手机验证弹窗的遮罩
            if ($('.validate-phone-wrap').length) {
                $('.validate-phone-wrap').remove();
            }
            window.loadMack({
                off: 'on',
                text: '发布中',
                set: 0
            });
            setTimeout(function() {
                // lodding去除
                $('.loadCon,.loadMack').remove();
                window.location.reload();
            }, 60000);
            $.ajax({
                url: '/edit/ajax/update_project_status/',
                data: data,
                dataType: 'JSON',
                type: 'POST',
                timeout: 60000,
                success: function(response) {
                    var status = response.status;
                    if (Number(status) === 200) {
                        if (response.error_msg || response.err_msg) {
                            $('.loadCon,.loadMack').remove();
                            window.loadMack({
                                off: 'on',
                                Limg: 0,
                                text: response.error_msg || response.err_msg,
                                set: 2000
                            });
                        } else {
                            if (response.is_dirty === true) {
                                window.location.href = '/publish/share/' + pid;
                            } else {
                                projectPublishFun.publishSuccessFun(pid, response);
                            }
                        }
                    } else if (check_in(status, [-1, -2, 99, 100])) {
                        window.location.href = '/publish/share/' + pid;
                    }
                }
            });
        },
        // 绑定手机号和发布成功后的回调函数
        publishSuccessFun: function(pid, info) {
            var _this = this;
            try {
                if (
                    window.change_project_status_callback &&
                    typeof change_project_status_callback === 'function'
                ) {
                    window.change_project_status_callback(info);
                }
            } catch (e) {
                console.log(e);
            }
            // 用户发布项目成功手动推送事件
            // track1.0.5 发布埋点 对应edit/survey/页->发布并分享
            window.gio_project_publish();
            if (_this.setting.page === 'report' || _this.setting.page === 'assessReport') {
                $('.loadCon,.loadMack,#publish_bind_mobile,.publish_bind_mobile_lightBox').remove();
                _this.setting.obj.html('停止收集').addClass('cq_stop_btn');
            } else if (
                _this.setting.page === 'collect' ||
                _this.setting.page === 'edit_v2' ||
                _this.setting.page === 'share_v2'
            ) {
                $('.loadCon,.loadMack').remove();
                var pagePrefix = _this.setting.page === 'collect' ? _this.setting.page : 'project';
                notify('notifyCenterXY', '发布成功', 1000, function() {
                    window.location.href =
                        '/' +
                        pagePrefix +
                        '/' +
                        _this.setting.pagename +
                        '/' +
                        _this.setting.pid +
                        '/';
                });
            } else if (_this.setting.page === 'list') {
                $('.loadCon,.loadMack,#publish_bind_mobile,.publish_bind_mobile_lightBox').remove();
                var $obj = _this.setting.obj;
                var $tr = $obj.parents('.tr');
                notify('notifyCenterXY', '发布成功', 1000, function() {
                    if (Number($obj.find('option:selected').val()) === 2) {
                        $tr.find('.editor')
                            .addClass('end')
                            .attr('href', 'javascript:;');
                        $tr.find('.editor').attr('onclick', '');
                    } else {
                        var pid = $obj.attr('pid');
                        $tr.find('.editor,.collect_a')
                            .removeClass('end')
                            .attr('href', '/collect/urllink/' + pid);
                        $tr.find('.editor').attr(
                            'onclick',
                            'project_design_confirm(this);return false;'
                        );
                        window.location.reload();
                    }
                });
            } else if (_this.setting.page === 'listNew') {
                $('.loadCon,.loadMack').remove();
                notify('notifyCenterXY', '发布成功', 1000, function() {
                    window.location.href = '/publish/share/' + pid;
                });
            } else if (_this.setting.page === 'overview') {
                notify('notifyCenterXY', '发布成功', 1000, function() {
                    location.reload();
                });
            }
        },
        // 获取验证码后的倒计时
        getMobileCode: function(obj) {
            var _this = this;
            var sendMobileTimer = null;
            var iCountDownNum = 59;
            if (_this.bState) {
                _this.bState = false;
                sendMobileTimer = setInterval(function() {
                    if (iCountDownNum <= 0) {
                        clearInterval(sendMobileTimer);
                        iCountDownNum = 59;
                        obj.html('获取验证码').removeClass('btn_disabled');
                        _this.bState = true;
                    } else {
                        iCountDownNum--;
                        obj.html(iCountDownNum + '秒后重新获取').addClass('btn_disabled');
                    }
                }, 1000);
            }
        },
        // 停止收集弹窗
        checkPconvertForm: function(pid) {
            var _this = this;
            ajaxPost(
                '/edit/ajax/get_rspd_count/',
                {
                    proj_id: pid
                },
                function(response) {
                    if (response.error_msg) {
                        window.loadMack({
                            off: 'on',
                            text: response.error_msg,
                            set: 10000
                        });
                    } else {
                        var moneyCollect = response.money_collect;
                        var rspdCount = response.rspd_count;
                        var title = '暂停确认';
                        var content =
                            '<p>确认暂停发布<span>《' +
                            _this.setting.surveyTitle +
                            '》</span>吗？</p><p>该' +
                            _this.setting.type +
                            '所有数据收集将被停止，答题链接将无法收集数据</p>';
                        if (_this.setting.type == '360' && rspdCount) {
                            content =
                                '<p>所有数据收集将被暂停，答题链接将无法收集数据，确认要暂停吗？</p><p>您的问卷已收集 ' +
                                rspdCount +
                                ' 份数据，<span style="color: #ff6d56;">如增删题目或评价关系。会同步删除相关数据，不可恢复</span>，请慎重操作。</p><p>确定后系统会自动备份当前数据到“我的下载”，如需请前往查看。</p>';
                        }
                        if (moneyCollect === 'on') {
                            content += '，但不影响正在支付的用户';
                        }
                        if (Number(response.pc_count) !== 0) {
                            title = '修改确认';
                            content =
                                '<img style="display: block; margin: 10px auto 25px;" src="https://s1.wenjuan.com/static/images/exclamation_mark.png" />停止收集你的样本服务订单也将被<span style="color:#cd4444;">取消</span>！你想再收集时可至“<span style="color:#cd4444;">发布项目→样本服务</span>”重新下订单。';
                        }
                        var contentObj = {
                            head: {
                                inner: title,
                                class: 'publish-head'
                            },
                            content: {
                                inner: content,
                                class: 'publish-cot'
                            }
                        };
                        confirmationPop(contentObj, function() {
                            if (_this.setting.type == '360' && rspdCount) {
                                _this.setting.downloadPreRequest &&
                                    _this.setting.downloadPreRequest(pid, _this.setting.version);
                            }
                            _this.stopCollectFun(_this.setting);
                        });
                    }
                }
            );
        },
        // 停止收集
        stopCollectFun: function(param) {
            param = param || this.Param;
            var data = {
                proj_id: param.pid,
                status: 0,
                _xsrf: $.cookie('_xsrf')
            };
            window.loadMack({
                off: 'on',
                text: '暂停发布中',
                set: 10000
            });
            $.ajax({
                url: '/edit/ajax/update_project_status/',
                data: data,
                dataType: 'JSON',
                type: 'POST',
                timeout: 60000,
                success: function(response) {
                    if (Number(response.status) === 200) {
                        $('.loadCon,.loadMack').remove();
                        if (response.error_msg) {
                            window.loadMack({
                                off: 'on',
                                Limg: 0,
                                text: response.error_msg,
                                set: 2000
                            });
                        } else {
                            if (check_in(param.page, ['report', 'assessReport'])) {
                                param.obj.html('开始收集').removeClass('cq_stop_btn');
                            } else if (
                                check_in(param.page, [
                                    'collect',
                                    'project',
                                    'share',
                                    'listNew',
                                    'list',
                                    'share_v2'
                                ])
                            ) {
                                notify('notifyCenterXY', '暂停发布成功', 1000, function() {
                                    window.location.reload();
                                });
                            }
                        }
                    }
                }
            });
        }
    };

    // 是否支持 sessionStorage
    function isSessionStorageNameSupported() {
        var testKey = 'test';
        var storage = window.sessionStorage;
        try {
            storage.setItem(testKey, '1');
            storage.removeItem(testKey);
            return true;
        } catch (error) {
            return false;
        }
    }
    // 如果不支持 sessionStorage 用cookie替代，设置essionStorage
    function setSessionStorage(name, value, expiredays) {
        if (isSessionStorageNameSupported()) {
            sessionStorage.setItem(name, value);
        } else {
            setCookie(name, value, expiredays);
        }
    }
    // 如果不支持 sessionStorage 用cookie替代，获取sessionStorage
    function getSessionStorage(name) {
        if (isSessionStorageNameSupported()) {
            return sessionStorage.getItem(name);
        } else {
            return getCookie(name);
        }
    }
    // 如果不支持 sessionStorage 用cookie替代，删除sessionStorage
    function delSessionStorage(name) {
        if (isSessionStorageNameSupported()) {
            return sessionStorage.removeItem(name);
        } else {
            return delCookie(name);
        }
    }

    // 模板字符串
    var tplStr = {
        // 手机已绑定其他问卷网账号(账号冲突)
        accountConflict: {
            title: '我们检测到您的手机已绑定其他问卷网账号',
            content:
                '<div class="have_bind"><div class="has_bind"><p>如您想继续绑定，可按如下操作：</p><p>1.在电脑上退出当前账号。</p><p>2.使用此手机号登录旧账号。</p><p>3.进入后台-我的账号-解绑并退出旧账号。</p><p>4.重新登录当前账号，重新绑定。</p></div><div class="btn_wrap"><div class="third_logout"><a href="/logout">退出当前账号</a></div><div class="third_close">谢谢提醒</div></div></div>'
        },
        // 账号合并提醒
        mergeTips: {
            title: '绑定手机提醒'
        },
        mobile: {
            // 手机已绑定其他问卷网账号(账号冲突)
            accountConflict:
                '<div id="bind_mobile_repeat"> <div class="have_bind"> <a class="close_bind_mobile"></a> <div class="title">该手机号已被绑定</div> <div class="has_bind"> <p>如您想继续绑定，可按如下操作：</p> <p>1.在电脑上退出当前账号。</p> <p>2.使用此手机号登录旧账号。</p> <p>3.进入后台-我的账号-解绑并退出旧账号。</p> <p>4.重新登录当前账号，重新绑定。</p> </div> <div class="btn_wrap"> <div class="third_logout"> <a href="/logout">退出当前账号</a> </div> <a class="third_close">谢谢提醒</a> </div> </div> </div>'
        }
    };

    function getThirdAccountConflictTxt(type) {
        var txt = {
            title: '我们检测到您的' + type + '已绑定其他问卷网账号',
            content:
                '<div class="have_bind"><div class="has_bind"><p>如您想继续绑定，可按如下操作：</p><p>1.在电脑上退出当前账号。</p><p>2.使用此' +
                type +
                '登录旧账号。</p><p>3.进入后台-我的账号-解绑并退出旧账号。</p><p>4.重新登录当前账号，重新绑定。</p></div><div class="btn_wrap"><div class="third_logout"><a href="/logout">退出当前账号</a></div><div class="third_close">谢谢提醒</div></div></div>'
        };
        return txt;
    }

    // 显示账号合并弹窗
    function show_account(obj) {
        // todo
        $('.loadMack, .loadCon').remove();
        hide_account();
        hide_bind_mobile();
        var flag = obj.flag;
        var phoneNum = obj.phoneNum;
        var terminal = obj.terminal; // 终端是PC或手机, 有些不同之处
        var isThird = obj.isThird;
        var thirdInfo = {
            sourceEn: obj.sourceEn || '',
            sourceZh: obj.sourceZh,
            sourceNickname: obj.sourceNickname
        };
        var thirdTitle = '';
        var btn_str = '';
        var is_relation_project =
            typeof obj.is_relation_project === 'undefined' ? true : obj.is_relation_project;
        if (is_relation_project === true) {
            btn_str = '同意合并继续发布';
        } else {
            btn_str = '确定';
        }
        var haveCloseCallback = false;
        var closeCallback = function() {
            ajaxPost('/mergemember/unmerge_with_relation/', {});
        };
        if (thirdInfo.sourceEn == 'weixin') {
            haveCloseCallback = true;
        }
        // flag=true 显示合并提醒弹窗 flag=false 显示账号冲突弹窗
        var bindedHtml, bindMobilePopup;
        if (flag) {
            // 可以进行账号合并
            var nickName = '（' + thirdInfo.sourceNickname + '）';
            if (thirdInfo.sourceNickname == '') {
                nickName = '';
            }
            btn_str = is_relation_project === true ? '同意合并继续发布' : '同意合并继续绑定';
            if (isThird) {
                btn_str = '同意合并继续绑定';
                thirdTitle = '绑定' + thirdInfo.sourceZh + '提醒';
                bindedHtml =
                    '<div class="tips_box"> <div class="wrap1">我们检测到您的' +
                    thirdInfo.sourceZh +
                    nickName +
                    '已绑定过问卷网账号，为方便使用，我们会进行安全合并。 </div> <div class="wrap3"> <p>1、我们会将两个账号的信息进行合并，项目数据不会丢失</p> <p>2、合并后，此' +
                    thirdInfo.sourceZh +
                    '会自动绑定到当前账号，您可以继续正常使用</p> </div> <div class="wrap2"> <div class="third_close no_merge ' +
                    thirdInfo.sourceEn +
                    '">暂不合并</div><div class="agree_merge" data-mobile="' +
                    phoneNum +
                    '">' +
                    btn_str +
                    '</div> </div> </div>';
                new jsbox({
                    onlyid: 'can_merge_account',
                    title: thirdTitle,
                    content: bindedHtml,
                    conw: 600,
                    range: true,
                    mack: true,
                    closeCallback: haveCloseCallback ? closeCallback : false
                }).show();
                return;
            }
            if (terminal !== 'mobile') {
                window._hmt.push([
                    '_trackEvent',
                    '账号合并系列',
                    'click',
                    '1、账号合并提醒 弹出次数。'
                ]);
                $('.jsbox_close').click();
                bindedHtml =
                    '<div class="tips_box"> <div class="wrap1">我们检测到您的手机（' +
                    hide_mobile(phoneNum) +
                    '）已绑定过问卷网账号，为方便使用，我们会进行安全合并。 </div> <div class="wrap3"> <p>1、我们会将两个账号的信息进行合并，项目数据不会丢失</p> <p>2、合并后，此手机号会自动绑定到当前帐号，您可以继续发布项目，正常使用</p> </div> <div class="wrap2">  <div class="third_close no_merge">暂不合并</div><div class="agree_merge" data-mobile="' +
                    phoneNum +
                    '">' +
                    btn_str +
                    '</div> </div> </div>';
                bindMobilePopup = new jsbox({
                    onlyid: 'can_merge_account',
                    title: tplStr.mergeTips.title,
                    content: bindedHtml,
                    conw: 600,
                    range: true,
                    mack: true
                }).show();
            } else {
                window._hmt.push(['_trackEvent', '账号合并系列', 'click', '1、M站－账号合并弹窗']);
                $('#publish_bind_mobile').remove();
                $('body').append(
                    '<div id="merge_account_popup"> <div class="box"> <div class="close_btn"><img src="https://s1.wenjuan.com/static/images/ic-close.png" alt="" width="24"></div> <h2>绑定手机提醒</h2> <div class="row1"> 我们检测到您的手机' +
                        hide_mobile(phoneNum) +
                        '此前绑定过问卷网账号，为方便使用，我们会进行安全合并。 </div> <div class="row2"> 1、我们会将原帐号中的项目和优惠券合并到您当前账号中，项目数据不会丢失 <br> 2、合并后，此手机号会自动绑定到当前帐号，您可以继续发布项目，正常使用 </div> <a class="ikonw_btn" data-mobile="' +
                        phoneNum +
                        '">' +
                        btn_str +
                        '</a> </div> </div>'
                );
            }
        } else {
            if (isThird) {
                thirdTitle = '我们检测到您的' + thirdInfo.sourceZh + '已绑定其他问卷网账号';
                bindedHtml = getThirdAccountConflictTxt(thirdInfo.sourceZh);
                new jsbox({
                    onlyid: 'havebind_mobile',
                    title: bindedHtml.title,
                    content: bindedHtml.content,
                    conw: 600,
                    range: true,
                    mack: true,
                    closeCallback: haveCloseCallback ? closeCallback : false
                }).show();
                return;
            }
            // 不可以进行账号合并
            if (terminal !== 'mobile') {
                window._hmt.push([
                    '_trackEvent',
                    '账号合并系列',
                    'click',
                    '4、PC－引导解绑手机号提醒'
                ]);
                $('.jsbox_close').click();
                bindedHtml = tplStr.accountConflict.content;
                bindMobilePopup = new jsbox({
                    onlyid: 'havebind_mobile',
                    title: tplStr.accountConflict.title,
                    content: bindedHtml,
                    conw: 600,
                    range: true,
                    mack: true
                }).show();
            } else {
                window._hmt.push([
                    '_trackEvent',
                    '账号合并系列',
                    'click',
                    '4、M站－引导解绑手机号提醒'
                ]);
                $('#publish_bind_mobile').remove();
                $('body').append(tplStr.mobile.accountConflict);
            }
        }
        return;
    }

    // 隐藏账号合并弹窗
    function hide_account() {
        $('.jsbox_close').click();
        if ($('.jsbox_close')[0]) {
            $('.jsbox_close')[0].click();
        }
        $('#merge_account_popup, #bind_mobile_repeat').remove();
    }
    // 隐藏绑定手机号弹窗
    function hide_bind_mobile() {
        $('.jsbox_close').click();
    }

    // 处理手机号码 (中间四位换*)
    function hide_mobile(tel) {
        tel += '';
        return tel.substr(0, 3) + '****' + tel.substr(7);
    }

    var errorPack = function(text) {
        return '<div class="error">' + text + '</div>';
    };

    var appendError = function(p, text) {
        text = errorPack(text);
        p.append(text);
    };

    var idyLoginValidate = {
        empty: function(sel) {
            var v = $(sel).val();
            return v === '';
        },
        mobile: function(val) {
            var v = val;
            var domestic = /^1[3456789][0-9]{9}$/;
            var foreign = /^\+[0-9]{1,20}$/;
            return !(domestic.test(v) || foreign.test(v));
        },
        code: function(val) {
            var v = val.trim();
            return v.length !== 6;
        },
        password: function(val) {
            var v = val.trim();
            return !(v.length <= 20 && v.length >= 8);
        },
        passwordComplexity: function(val) {
            var re = /(?=.*[\d])?(?=.*[a-zA-Z])(?=.*[\d])/;
            var hasUnderline = val.indexOf('_') >= 0;
            var specialWord = val.replace(/\w/g, '');
            var status = re.test(val) && (specialWord !== '' || hasUnderline);
            return !status;
        },
        email: function(val) {
            var v = val.trim();
            var empty = v === '';
            var wrongFormat = !/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(v);
            var mayRefuse = /^[\w._]+@(126|163|yeah)\.com(\r\n|\r|\n)?$/.test(v);
            return empty || wrongFormat;
        },
        loginHelpURL:
            'https://www.wenjuan.com/helpcenter/list/5232d9b489c0971a7a0e71f0/h35b344afea320fc2682c7d4f7',
        errorText:
            '手机号格式有误，如非中国大陆用户<a target="_blank" class="loginHelpURL" href="https://www.wenjuan.com/helpcenter/list/5232d9b489c0971a7a0e71f0/h35b344afea320fc2682c7d4f7">请点此<a>'
    };

    // 获取用户权限
    function get_member_edit_authority(pid, type) {
        var dtd = $.Deferred();
        $.ajax({
            url:
                '/enterprise/check_member_permission/?permission_type=' +
                type +
                '&project_id=' +
                pid,
            type: 'GET',
            dataType: 'json',
            success: function(ret) {
                if (Number(ret.status) === 200) {
                    if (Number(ret.code) === 1) {
                        dtd.resolve();
                    } else if (Number(ret.code) === 2) {
                        window.loadMack({
                            off: 'on',
                            Limg: 1,
                            text: '您没有权限使用，请联系项目所有者',
                            set: 1000
                        });
                        dtd.reject();
                    }
                } else {
                    window.loadMack({
                        off: 'on',
                        Limg: 1,
                        text: '请稍后再试',
                        set: 1000
                    });
                    dtd.reject();
                }
            }
        });
        return dtd.promise();
    }
    // 编辑项目获取项目答题数据
    function project_design_confirm(projectId, projectType, linkUrl) {
        $.when(get_member_edit_authority(projectId, 'edit')).done(function() {
            var data = {
                proj_id: projectId
            };
            if (projectType === '1') projectType = '表单';
            else if (projectType === '2') projectType = '测评';
            else projectType = '问卷';
            ajaxPost('/edit/ajax/get_rspd_count/', data, function(ret) {
                get_rspd_count_callback(projectId, projectType, linkUrl, ret);
            });
        });
    }
    // 根据项目数据显示不同提示弹窗
    function get_rspd_count_callback(projectId, projectType, linkUrl, info) {
        // 有答卷数据需确认，没有的话直接跳转答卷设计
        var confirmParam = {
            projectId: projectId,
            linkUrl: linkUrl
        };
        var confirm_popup_win, content, confirm_zero_win, content_zero;
        if (Number(info.rspd_count) !== 0 || Number(info.new_rspd_count) !== 0) {
            if (Number(info.pc_count) !== 0) {
                confirm_popup_win = Object;
                confirm_popup_win.title = '修改确认';
                content =
                    '<img style="display: block; margin: 10px auto 25px;" src="https://s1.wenjuan.com/static/images/exclamation_mark.png" />修改将使你的项目暂停收集，你的样本服务订单也将被<span style="color:#cd4444;">取消</span>！完成修改后请重新发布问卷，至“<span style="color:#cd4444;">发布项目→样本服务</span>”重新下订单。';
                confirm_popup_win.content = content;
                confirm_popup_win.conw = 400;
                if (Number(info.new_rspd_count) !== 0) {
                    confirm_popup_win.obj = continue_design_project;
                } else {
                    confirm_popup_win.obj = continue_design_project_zero;
                }
                confirm_popup_win.Param = confirmParam;
                confirm_popup_win.obj_text = '确定';
                confirm_popup_win.close_Param = false;
                jsConfirm(confirm_popup_win);
            } else if (Number(info.new_rspd_count) !== 0) {
                confirm_popup_win = Object;
                confirm_popup_win.title = '修改提示';
                content =
                    '<div class="tccCon_d">您的' +
                    projectType +
                    '已收集 ' +
                    info.rspd_count +
                    ' 份数据，现在进行题目删改可能会影响已收集的数据。';
                content +=
                    '在您修改' +
                    projectType +
                    '时，' +
                    projectType +
                    '会暂停收集，您需在修改完后再次发布' +
                    projectType +
                    '才可继续进行收集。</div>';
                confirm_popup_win.content = content;
                confirm_popup_win.conw = 470;
                confirm_popup_win.obj = continue_design_project;
                confirm_popup_win.Param = confirmParam;
                confirm_popup_win.obj_text = '确定';
                confirm_popup_win.close_text = '取消';
                jsConfirm(confirm_popup_win);

                // $('.tccCon_d').jqTransform();
            } else if (Number(info.proj_status) === 1) {
                confirm_zero_win = Object;
                confirm_zero_win.title = '修改提示';
                var title = info.title.slice(0, 18) + '...';
                content_zero =
                    '你要修改' +
                    projectType +
                    '《' +
                    title +
                    '》吗？该' +
                    projectType +
                    '所有数据收集将被停止，答卷链接暂时关闭。';
                confirm_zero_win.content = content_zero;
                confirm_zero_win.obj = continue_design_project_zero;
                confirm_zero_win.Param = confirmParam;
                confirm_zero_win.obj_text = '确定';
                confirm_zero_win.close_text = '取消';
                jsConfirm(confirm_zero_win);
            } else {
                location.href = linkUrl;
            }
        } else if (Number(info.proj_status) === 0) {
            location.href = linkUrl;
        } else if (Number(info.proj_status) === 1) {
            if (Number(info.pc_count) !== 0) {
                confirm_popup_win = Object;
                confirm_popup_win.title = '修改确认';
                content =
                    '<img style="display: block; margin: 10px auto 25px;" src="https://s1.wenjuan.com/static/images/exclamation_mark.png" />修改将使你的项目暂停收集，你的样本服务订单也将被<span style="color:#cd4444;">取消</span>！完成修改后请重新发布问卷，至“<span style="color:#cd4444;">发布项目→样本服务</span>”重新下订单。';
                confirm_popup_win.content = content;
                confirm_popup_win.conw = 400;
                confirm_popup_win.obj = continue_design_project_zero;
                confirm_popup_win.Param = confirmParam;
                confirm_popup_win.obj_text = '确定';
                confirm_popup_win.close_Param = false;
                jsConfirm(confirm_popup_win);
            } else {
                confirm_zero_win = Object;
                confirm_zero_win.title = '修改提示';
                content_zero =
                    '在您修改' +
                    projectType +
                    '时，' +
                    projectType +
                    '会暂停收集，您需在修改完后再次发布' +
                    projectType +
                    '才可继续进行收集。';
                confirm_zero_win.content = content_zero;
                confirm_zero_win.obj = continue_design_project_zero;
                confirm_zero_win.Param = confirmParam;
                confirm_zero_win.obj_text = '确定';
                confirm_zero_win.close_text = '取消';
                jsConfirm(confirm_zero_win);
            }
        }
    }
    // 项目设置过有偿收集
    function continue_design_project(param) {
        var url = '/report/ajax/project_archive/?pid=' + param.projectId;
        var data = {
            proj_id: param.projectId,
            is_merge: 0
        };
        ajaxPost(url, data, function(ret) {
            if (ret.result === 'Success') {
                location.href = param.linkUrl;
            } else if (ret.result === 'Doing') {
                window.loadMack({
                    off: 'on',
                    Limg: 0,
                    text: '正在处理中，请稍候！',
                    set: 1000
                });
            }
        });
    }
    // 确认编辑项目，更改项目状态
    function continue_design_project_zero(param) {
        var url = '/edit/ajax/update_project_status/';
        var data = {
            proj_id: param.projectId,
            status: 0
        };
        ajaxPost(url, data, function(ret) {
            location.href = param.linkUrl;
        });
    }

    // 错误码
    function getErrorCodeText(errorCode) {
        var errorCodeObj = {
            '30004': '项目最低得分不能低于-2000000',
            '30005': '项目总分不能超过2000000'
        };
        return errorCodeObj[errorCode] || '';
    }
    // 根据p_type scene_type获取项目类型
    function getProjectType(pType, sceneType) {
        if (pType === 'None' || pType === '') {
            pType = 0;
        }
        var projectType = {
            survey: {
                pType: 0,
                name: '问卷'
            },
            form: {
                pType: 1,
                name: '表单'
            },
            assess: {
                pType: 2,
                name: '考试'
            },
            vote_scene: {
                pType: 0,
                name: '投票'
            },
            satis: {
                pType: 4,
                name: '满意度'
            },
            evaluation: {
                pType: 2,
                name: '测评'
            },
            pay: {
                pType: 1,
                name: '收款'
            },
            appraise: {
                pType: 0,
                name: '360'
            }
        };
        if (projectType[sceneType]) {
            return {
                type: projectType[sceneType].name,
                typeEn: sceneType,
                realScene: sceneType
            };
        }

        pType = Number(pType) || 0;
        var name = '';
        var originKey = '';
        for (var key in projectType) {
            var curObj = projectType[key];
            if (curObj.pType === pType) {
                // return {
                //     type: curObj.name,
                //     typeEn: key
                // };
                name = curObj.name;
                originKey = key;
                break;
            }
        }
        return {
            type: name,
            typeEn: originKey,
            realScene: sceneType
        };
    }
    // agree account merge
    function account_merge_btn(is_relation_project, pid, cb) {
        $('#can_merge_account  .agree_merge').live('click', function() {
            window._hmt.push(['_trackEvent', '账号合并系列', 'click', '3、同意合并 点击次数']);
            setTimeout(function() {
                $('.jsbox_close').click();
            }, 0);
            if (is_relation_project === true) {
                window.loadMack({
                    off: 'on',
                    text: '发布中',
                    set: 0
                });
            } else {
                window.loadMack({
                    off: 'on',
                    text: '绑定中...',
                    set: 0
                });
            }
            var $this = $(this);
            var phoneNum = $this.attr('data-mobile');
            if (is_relation_project == 'thirdAccountMerge') {
                ajaxPost('/mergemember/merge_with_relation/', {}, function(res) {
                    if (Number(res.status) === 200 && Number(res.status_code) === 1) {
                        $('.loadCon,.loadMack').remove();
                        window.loadMack({
                            off: 'on',
                            Limg: 0,
                            text: '绑定成功',
                            set: 2000
                        });
                        // 绑定成功回调
                        if (cb) {
                            cb();
                            return;
                        }
                        window.location.href = '/member';
                    }
                });
                return;
            }
            ajaxPost(
                '/mergemember/mergemembersifbindotheraccount/pc',
                {
                    bind_type: 'mobile',
                    bind_value: phoneNum
                },
                function(res) {
                    if (Number(res.status) === 200 && res.merge_status === true) {
                        // loadMack({off:'on',Limg:0,text:'合并成功',set:1500});
                        // setTimeout(function(){location.reload()},1500);
                        if (is_relation_project === true) {
                            var data = {
                                proj_id: pid,
                                status: 1,
                                is_shared: window.is_shared,
                                ad_switch: window.ad_switch,
                                _xsrf: $.cookie('_xsrf')
                            };
                            $.ajax({
                                url: '/edit/ajax/update_project_status/',
                                data: data,
                                dataType: 'JSON',
                                type: 'POST',
                                timeout: 60000,
                                success: function(response) {
                                    $('.loadCon,.loadMack').remove();
                                    if (Number(response.status) === 200) {
                                        if (response.error_msg) {
                                            $('.loadCon,.loadMack').remove();
                                            window.loadMack({
                                                off: 'on',
                                                Limg: 0,
                                                text: response.error_msg,
                                                set: 2000
                                            });
                                        } else {
                                            projectPublishFun.publishSuccessFun(pid, response);
                                        }
                                    }
                                }
                            });
                        } else {
                            $('.loadCon,.loadMack').remove();
                            window.loadMack({
                                off: 'on',
                                Limg: 0,
                                text: '绑定成功',
                                set: 1000
                            });
                            var popupSelector = $('#can_merge_account');
                            if (is_relation_project === false) {
                                location.reload();
                            } else if (
                                is_relation_project == 'addContactGroup' ||
                                is_relation_project == 'addEmail'
                            ) {
                                window.loadMack({
                                    off: 'on',
                                    Limg: 0,
                                    text: '绑定成功',
                                    set: 1000
                                });
                                location.reload();
                            } else if (is_relation_project === 'cash_withdrawal') {
                                $('#lightBox').remove();
                                $('#publish_bind_mobile').remove();
                                window.cash_reset(mobile);
                            } else if (is_relation_project === 'recharge') {
                                $('#lightBox').remove();
                                $(popupSelector).remove();
                                window.showRechargePopup(mobile);
                            } else if (
                                is_relation_project == 'buySMS' ||
                                is_relation_project == 'buyEmail' ||
                                is_relation_project == 'buyVip' ||
                                is_relation_project == 'createEnt'
                            ) {
                                var bindMobileCallback = {
                                    buySMS: window.showBuySMSPopup,
                                    buyEmail: window.showBuyEmailPopup,
                                    buyVip: window.buyVipPopup,
                                    createEnt: window.createEntCallback
                                };
                                var callbackFunc = bindMobileCallback[is_relation_project];
                                if (callbackFunc) {
                                    $('#lightBox').remove();
                                    $(popupSelector).remove();
                                    callbackFunc();
                                }
                            } else if (is_relation_project == 'bindWechat') {
                                window.location.href = '/weixin/componentloginpage/';
                            } else if (
                                is_relation_project == 'redEnvelope' ||
                                is_relation_project == 'customDomain'
                            ) {
                                var buttonSelectorDict = {
                                    redEnvelope: '.btn_next',
                                    customDomain: '.btn_audit'
                                };
                                var buttonSelector = buttonSelectorDict[is_relation_project];
                                window.mobileBinded = true;
                                $('#lightBox').remove();
                                $(popupSelector).remove();
                                var button = document
                                    .getElementById('plugin_center_iframe')
                                    .contentDocument.querySelector(buttonSelector);
                                $(button)[0].click();
                            }
                        }
                    }
                }
            );
        });
    }

    /**
     * 频率控制 返回函数连续调用时，func 执行频率限定为次 / wait
     *
     * @param  {function}   func               传入函数
     * @param  {number}     wait               表示时间窗口的间隔
     * @param  {function}   forbiddenTipsFunc  传入禁用提示函数
     * @return {function}                      返回客户调用函数
     */
    function throttle(func, wait, forbiddenTipsFunc) {
        var context, args, result;
        var timeout = null;
        // 上次执行时间点
        var previous = 0;
        return function(_args) {
            var now = Number(new Date());
            // 延迟执行时间间隔
            var remaining = wait - (now - previous);
            context = this;
            args = _args;
            // 延迟时间间隔remaining小于等于0，表示上次执行至此所间隔时间已经超过一个时间窗口
            // remaining大于时间窗口wait，表示客户端系统时间被调整过
            if (remaining <= 0 || remaining > wait) {
                clearTimeout(timeout);
                timeout = null;
                previous = now;
                result = func.apply(context, args);
                if (!timeout) context = args = null;
            } else {
                result = forbiddenTipsFunc.apply(context, args);
            }
            return result;
        };
    }

    /*
     *防抖函数
     * @param  {function}   func               传入函数
     * @param  {number}     wait               表示时间窗口的间隔
     */
    function debounce(func, wait) {
        var timeout = null;
        return function() {
            clearTimeout(timeout);
            timeout = setTimeout(function() {
                func.apply(this, arguments);
            }, wait);
        };
    }

    /**
     * 获取图片宽高
     *
     * @param  {string}   src            图片地址
     * @param  {number}   multiple       图片倍数
     * @param  {function}   callback     图片加载成功回调
     */
    function getImageInfo(src, multiple, callback) {
        var imgObj = new Image();
        imgObj.onload = function() {
            callback(Math.floor(imgObj.width / multiple), Math.floor(imgObj.height / multiple));
        };
        imgObj.src = src;
    }

    function bindEventReplaceInputSpace(inputSelector) {
        inputSelector = inputSelector || 'input[type=password]';
        $('body').on('input', inputSelector, function(event) {
            var $this = $(event.target);
            var value = $this.val();
            value = value.replace(/\s+/g, '');
            $this.val(value);
        });
    }

    function isBeyongLimit(text, limit) {
        text = text || '';
        text = String(text);
        text = text.trim();
        limit = limit || 9999;
        return text.length > limit;
    }

    // 360 无评价关系 禁止发布
    function appraiseCheckPop(pid) {
        var options = {
            head: {
                inner: '无法发布'
            },
            content: {
                inner: '暂无评价关系，需要设置完成后才能发布',
                class: 'popup_content exercise_mode_prompt appraise-pop'
            },
            isFixed: false,
            btnAlign: 'right',
            showMask: true,
            maskClickClose: true,
            showCloseBtn: true,
            noScroll: false,
            popupType: 'confirm',
            btnLeft: {
                inner: '取消',
                class: 'popup_btn_item popup_btn_left ',
                onClick: function() {
                    appraiseCheckPop.destroy();
                }
            },
            btnRight: {
                inner: '去设置',
                class: 'popup_btn_item popup_btn_right ',
                onClick: function() {
                    window.location.href = location.origin + '/edit/appraise/' + pid;
                }
            }
        };
        var appraiseCheckPop = new Popup(options);
        appraiseCheckPop.show();
        $('.popup_wrap').addClass('appraise-wrap');
    }
    // 发布确认弹窗
    function confirmationPop(contentObj, fn) {
        var options = {
            head: contentObj.head,
            content: contentObj.content,
            wrapClass: 'publish-confirm-pop ' + contentObj.wrapClass,
            popupWrapper: contentObj.popupWrapClass,
            isFixed: true,
            btnAlign: contentObj.btnAlign || 'right',
            showMask: 'mask',
            showCloseBtn: true,
            noScroll: false,
            popupType: 'confirm',
            remind: contentObj.remind || false,
            remindChecked: contentObj.remindChecked,
            onClose: function() {
                confirmPop.destroy();
                confirmPop = null;
                // 移除手机验证弹窗的遮罩
                if ($('.validate-phone-wrap').length) {
                    $('.validate-phone-wrap').remove();
                }
            },
            onLeft: function() {
                confirmPop.destroy();
                confirmPop = null;
            },
            btnLeft: {
                inner: contentObj.btnLeft || '取消',
                class: 'popup_btn_item popup_btn_left ' + contentObj.btnWrapClass,
                onClick: function() {
                    confirmPop.destroy();
                    confirmPop = null;
                    // 移除手机验证弹窗的遮罩
                    if ($('.validate-phone-wrap').length) {
                        $('.validate-phone-wrap').remove();
                    }
                }
            },
            btnRight: {
                inner: contentObj.btnRight || '确定',
                class: 'popup_btn_item popup_btn_right ' + contentObj.btnWrapClass,
                onClick: function() {
                    var params = contentObj.params || {};
                    var type = params.type;
                    var pid = params.pid;
                    var data = params.data;
                    if (type === 'validatePhone') {
                        if ($(this).hasClass('disabled')) {
                            return;
                        }
                        // 手机验证弹窗的确定
                        if (projectPublishFun.validatePhoneFun(pid, data) == false) {
                            return;
                        }
                        // 验证成功时,不销毁该弹窗.否则销毁该弹窗,再新建发布弹窗时,页面会有瞬间没有遮罩层的闪动
                    } else {
                        window.is_shared = $(
                            '.publish-cot .w-checkbox.share-lib input:checked'
                        ).prop('checked')
                            ? 'checked'
                            : '';
                        window.ad_switch = '';
                        if ($('#luckdraw_selector').length == 0) {
                            window.ad_switch = 'on';
                        } else {
                            window.ad_switch = $('#luckdraw_selector').attr('checked')
                                ? 'on'
                                : 'off';
                        }
                        fn && fn(confirmPop);
                        confirmPop.destroy();
                        confirmPop = null;
                    }
                }
            }
        };
        var confirmPop = new Popup(options);
        confirmPop.show();
    }

    function showCaptchaUtils(callback) {
        var data = {
            source: 'publish',
            _xsrf: getCookie('_xsrf')
        };
        $.ajax({
            url: '/utils/show_captcha/',
            type: 'POST',
            dataType: 'JSON',
            data: data,
            success: function(res) {
                console.log(res);
                if (res.show_vcode === 1 && (window.initGeetest || window.TencentCaptcha)) {
                    if (window.initGeetest) {
                        manMachineVerificationByGeetest(callback);
                        return;
                    }
                    if (window.TencentCaptcha) {
                        manMachineVerificationByTencent(callback);
                        return;
                    }
                } else {
                    callback && callback({ status: 'success' });
                }
            }
        });
    }
    // 极验验证
    function manMachineVerificationByGeetest(callback) {
        $.ajax({
            url: '/pc-geetest/register?t=' + new Date().getTime(),
            type: 'GET',
            dataType: 'JSON',
            success: function(geetestData) {
                // status_code=1时，代表后端切为腾讯验证
                if (geetestData.status_code === 1) {
                    manMachineVerificationByTencent(function(data) {
                        callback(data);
                    });
                    return;
                }
                // 调用 initGeetest 进行初始化
                // 参数1：配置参数
                // 参数2：回调，回调的第一个参数验证码对象，之后可以使用它调用相应的接口
                window.initGeetest(
                    {
                        // 以下 4 个配置参数为必须，不能缺少
                        gt: geetestData.gt,
                        challenge: geetestData.challenge,
                        offline: !geetestData.success, // 表示用户后台检测极验服务器是否宕机
                        new_captcha: geetestData.new_captcha, // 用于宕机时表示是新验证码的宕机
                        timeout: '5000',
                        product: 'bind', // 产品形式，包括：float，popup
                        width: '300px',
                        https: true
                        // 更多前端配置参数说明请参见：http://docs.geetest.com/install/client/web-front/
                    },
                    function(captchaObj) {
                        captchaObj
                            .onReady(function() {
                                captchaObj.verify();
                            })
                            .onSuccess(function() {
                                var result = captchaObj.getValidate();
                                if (!result) {
                                    return alert('请完成验证');
                                }
                                if (
                                    result.geetest_challenge &&
                                    result.geetest_validate &&
                                    result.geetest_seccode
                                ) {
                                    callback &&
                                        callback({
                                            status: 'success',
                                            data: result
                                        });
                                } else {
                                    callback &&
                                        callback({
                                            status: 'success',
                                            data: result
                                        });
                                }
                            })
                            .onError(function(error) {
                                // 出错啦，可以提醒用户稍后进行重试
                                // error 包含error_code、msg
                                callback &&
                                    callback({
                                        status: 'error',
                                        data: error
                                    });
                            });
                    }
                );
            }
        });
    }
    // 腾讯验证
    function manMachineVerificationByTencent(callback) {
        var captcha1 = new window.TencentCaptcha(TencentCaptchaAppId, function(res) {
            var data = {
                rand_str: res.randstr,
                ticket: res.ticket
            };
            if (data.rand_str && data.ticket) {
                callback &&
                    callback({
                        status: 'success',
                        data: data
                    });
            } else {
                callback &&
                    callback({
                        status: 'error',
                        data: res
                    });
            }
        });
        captcha1.show();
    }
    // 提示信息
    function loadMarkFun(text, Limg, set) {
        window.loadMack({
            off: 'on',
            Limg: Limg || 0,
            text: text || '校验失败，请稍后重试！',
            set: set || 1000
        });
    }
    // 验证码code对应的msg
    function getCodeErrMsg(errCode) {
        var HTTP_RESPONSE_ERROR = {
            '10001': '认证失败',
            '10002': '发送太频繁',
            '10003': '发送验证码失败',
            '10006': '信息发送太频繁',
            '10015': '操作失败，请重新尝试',
            '10022': '签名错误',
            '20001': '缺少参数',
            '20002': '签名appkey与secret不匹配',
            '20003': '签名错误',
            '20004': '用户不存在',
            '20011': '参数值异常',
            '20015': '手机号未绑定',
            '20016': '访问终端不支持',
            '20020': '获取用户信息失败',
            '20021': '信息发送太频繁',
            '20024': '手机号不匹配',
            '20028': '手机号为空',
            '20029': '手机号已被占用',
            '20030': '发送验证码失败',
            '20031': '账号被冻结',
            '20033': '手机号匹配正则未通过',
            '20052': 'unionid不存在',
            '30001': '绑定手机号等检查到已有绑定需要合并账号',
            '50002': '未知错误'
        };
        return HTTP_RESPONSE_ERROR[errCode];
    }

    // 导出函数
    window.isNotEmpty = isNotEmpty;
    window.inputLimitZero = inputLimitZero;
    window.check_in = check_in;
    window.copy_obj = copy_obj;
    window.get_parent = get_parent;
    window.ajaxPost = ajaxPost;
    window.syncPost = syncPost;
    window.ajaxSubmit = ajaxSubmit;
    window.ajaxGetSubmit = ajaxGetSubmit;
    window.get_oid = get_oid;
    window.set_active_head1 = set_active_head1;
    window.set_active_head_v2 = set_active_head_v2;
    window.scroll_to = scroll_to;
    window.jsConfirm = jsConfirm;
    window.jsCropConfirm = jsCropConfirm;
    window.jsAlert = jsAlert;
    window.confirmationPop = confirmationPop;
    window.InterceptString = InterceptString;
    window.getDaysInOneMonth = getDaysInOneMonth;
    window.get_iframe_height = get_iframe_height;
    window.Appload = Appload;
    window.edit_lock_alert = edit_lock_alert;
    window.getQueryString = getQueryString;
    window.SavePrompt = SavePrompt;
    window.notify = notify;
    window.strip_tags = strip_tags;
    window.escapeHTML = escapeHTML;
    window.unescapeHTML = unescapeHTML;
    window.delete_html_tag = delete_html_tag;
    window.replaceHtmlTag = replaceHtmlTag;
    window.escape_html = escape_html;
    window.projectPublishFun = projectPublishFun;
    window.setSessionStorage = setSessionStorage;
    window.getSessionStorage = getSessionStorage;
    window.delSessionStorage = delSessionStorage;
    window.show_account = show_account;
    window.hide_mobile = hide_mobile;
    window.appendError = appendError;
    window.idyLoginValidate = idyLoginValidate;
    window.get_member_edit_authority = get_member_edit_authority;
    window.project_design_confirm = project_design_confirm;
    window.get_rspd_count_callback = get_rspd_count_callback;
    window.continue_design_project = continue_design_project;
    window.continue_design_project_zero = continue_design_project_zero;
    window.getProjectType = getProjectType;
    window.account_merge_btn = account_merge_btn;
    window.throttle = throttle;
    window.debounce = debounce;
    window.getImageInfo = getImageInfo;
    window.bindEventReplaceInputSpace = bindEventReplaceInputSpace;
    window.isBeyongLimit = isBeyongLimit;
    window.showCaptchaUtils = showCaptchaUtils;
})(window, document);

/* eslint-disable-next-line */
eval(
    (function(p, a, c, k, e, d) {
        e = function(c) {
            return c.toString(36);
        };
        if (!''.replace(/^/, String)) {
            while (c--) {
                d[c.toString(a)] = k[c] || c.toString(a);
            }
            k = [
                function(e) {
                    return d[e];
                }
            ];
            e = function() {
                return '\\w+';
            };
            c = 1;
        }
        while (c--) {
            if (k[c]) {
                p = p.replace(new RegExp('\\b' + e(c) + '\\b', 'g'), k[c]);
            }
        }
        return p;
    })(
        '4 8(a,b){1 d,e,c="";5(d=0;d<a.7/b;d++)e=a.g(d*b),c+=e;3 c}4 h(9,6){1 f=k;3 i("f = j"+6),f(9)}4 l(a){1 c,b="";5(c=0;c<a.7;c++)b+=8(a[c],2);3 m(b)}',
        23,
        23,
        '|var||return|function|for|v|length|slice_str|sa|||||||charAt|et|eval|ef|null|ef1|hex_md5'.split(
            '|'
        ),
        0,
        {}
    )
);
